0

I am creating an android app to login the users by using Mobile number OTP verification from fire-base This is how the database looks like

This is the loggin activity where i am passing the value "mobile" to OTP typing activity( here LoginActivity.java)

  CardView card_view = findViewById(R.id.cardView);
    card_view.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {


         String mobile = editTextMobile.getText().toString().trim();

            if(mobile.isEmpty() || mobile.length() < 10){
              editTextMobile.setError("Enter a valid mobile");
                editTextMobile.requestFocus();



                   return;
                 }

                 if(mobile.length()>10)
            {
                editTextMobile.setError("Enter a valid mobile");
                editTextMobile.requestFocus();
                return;

            }



           Intent intent = new Intent(LoginActivity.this, VerifyPhoneActivity.class);
               intent.putExtra("mobile", mobile);
                  startActivity(intent);





        }


    });

This is where user will enter the OTP (VerifyPhoneActivity.java). If the OTP is correct and if the mobile number is not exist in database already then user can go to sigh up up activity

 public FirebaseAuth.AuthStateListener authListener;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_verify_phone);

    mAuth= FirebaseAuth.getInstance();
    mDatabase = FirebaseDatabase.getInstance().getReference();
    sendVerificationCode();




    findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {



        @Override
        public void onClick(View v) {




            verifySignInCode();





        }
    });



}


private void verifySignInCode()


    {

        final EditText fd = (EditText) findViewById(R.id.et1);
        String value= fd.getText().toString();



        final EditText sd = (EditText) findViewById(R.id.et2);
        String value1= sd.getText().toString();
        // int finalValue1=Integer.parseInt(value1);



        EditText td = (EditText) findViewById(R.id.et3);
        String value2= td.getText().toString();


        EditText fod = (EditText) findViewById(R.id.et4);
        String value3= fod.getText().toString();


        EditText fid = (EditText) findViewById(R.id.et5);
        String value4= fid.getText().toString();


        EditText sid = (EditText) findViewById(R.id.et6);
        String value5= sid.getText().toString();


        code = value + value1+value2+value3+value4+value5;



        PhoneAuthCredential credential = PhoneAuthProvider.getCredential(codesent, code);

        signInWithPhoneAuthCredential(credential);


    }

    private void signInWithPhoneAuthCredential(PhoneAuthCredential credential) {
    mAuth.signInWithCredential(credential)
            .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                @RequiresApi(api = Build.VERSION_CODES.KITKAT)
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                    if (task.isSuccessful()) {




                       DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
                        FirebaseUser userid = FirebaseAuth.getInstance().getCurrentUser();

                        final String uid = userid.getUid();
                        ref.child("Users");
                        ref.child(mobile).child(uid);

                        ref.addListenerForSingleValueEvent(new ValueEventListener() {


                            @Override
                            public void onDataChange(DataSnapshot dataSnapshot) {
                                if (dataSnapshot.exists()) {


                                    Toast.makeText(getApplicationContext(), "already account there",
                                            Toast.LENGTH_LONG).show();



                                } else {




                                    Intent intent = new Intent(VerifyPhoneActivity.this, Signup.class);

                                    intent.putExtra("mobile", mobile);

                                    startActivity(intent);

                                    Intent myIntent = new Intent(VerifyPhoneActivity.this, Signup.class);
                                    startActivity(myIntent);



                                    Toast.makeText(getApplicationContext(), "account not exist",
                                            Toast.LENGTH_LONG).show();

                                }
                            }

                            @Override
                            public void onCancelled(DatabaseError databaseError) {

                            }
                        });


                        Toast.makeText(getApplicationContext(), "login success",
                                Toast.LENGTH_LONG).show();




                    } else {

                        Toast.makeText(getApplicationContext(), "login faild",
                                Toast.LENGTH_LONG).show();


                        // Sign in failed, display a message and update the UI
                       // Log.w(TAG, "signInWithCredential:failure", task.getException());
                        if (task.getException() instanceof FirebaseAuthInvalidCredentialsException) {
                            // The verification code entered was invalid

                            Toast.makeText(getApplicationContext(), "OTP was wrong",
                                    Toast.LENGTH_LONG).show();

                        }
                    }
                }
            });
}

PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallbacks=new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
    @Override
    public void onVerificationCompleted(PhoneAuthCredential phoneAuthCredential) {
        Toast.makeText(getApplicationContext(), "verification completed",
                Toast.LENGTH_LONG).show();
    }

    @Override
    public void onVerificationFailed(FirebaseException e) {

        Toast.makeText(getApplicationContext(), "sending faild"+e,
                Toast.LENGTH_LONG).show();
    }

    @Override
    public void onCodeSent(String s, PhoneAuthProvider.ForceResendingToken forceResendingToken) {
       // super.onCodeSent(s, forceResendingToken);


        Toast.makeText(getApplicationContext(), "sent",
                Toast.LENGTH_LONG).show();
        codesent=s;

    }
};

private void sendVerificationCode() {


    Intent intent = getIntent();
    mobile = intent.getStringExtra("mobile");


    Toast.makeText(getApplicationContext(), mobile,
            Toast.LENGTH_LONG).show();
    String phonenumber= "+91"+mobile;

  //  Toast.makeText(getApplicationContext(), phonenumber,
    //        Toast.LENGTH_LONG).show();

    PhoneAuthProvider.getInstance().verifyPhoneNumber(
            phonenumber,        // Phone number to verify
            60,                 // Timeout duration
            TimeUnit.SECONDS,   // Unit of timeout
            this,               // Activity (for callback binding)
            mCallbacks);        // OnVerificationStateChangedCallbacks

}

}

And at last this is where (Signup.java) am getting error (i will mension below)

public class Signup extends Activity {


String name;
String address;
String pincode;
String city;
String mobile;
DatabaseReference mDatabase;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_signup);




    Intent intent = getIntent();
    mobile = intent.getStringExtra("mobile");







    findViewById(R.id.signupbutton).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {




            EditText nameedittext = (EditText) findViewById(R.id.nametextview);
             name= nameedittext.getText().toString();


            EditText addressedittext = (EditText) findViewById(R.id.addresstextview);
            address= addressedittext.getText().toString();


            EditText pincodeedittext = (EditText) findViewById(R.id.picodetextview);
            pincode= pincodeedittext.getText().toString();

            EditText cityedittext = (EditText) findViewById(R.id.citytextview);
            city= cityedittext.getText().toString();






            DatabaseReference ref = FirebaseDatabase.getInstance().getReference();


              ref = ref.child("Users");
            FirebaseUser userid = FirebaseAuth.getInstance().getCurrentUser();

            final String uid = userid.getUid();
            ref = ref.child(mobile).child(uid);


              Map<String, String> userData = new HashMap<String, String>();

             userData.put("Name", name);
             userData.put("Address", address);
             userData.put("Pin", pincode);
             userData.put("City", city);






              ref.setValue(userData);



        }
    });




}
}

I am facing 2 problems

  • I am getting the error below and app crashes app relaunching the same activity (Signup.java) if i enter the details again it will get updated in db as screenshot above (in case i am the first user)
  • If the first user signed up and his mobile got registered then when the second user sign up it is showing "login success" and account "already there" 2 toasts

Error am getting

2019-03-15 16:57:40.706 1932-1932/com.example.meenvandi E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.meenvandi, PID: 1932 java.lang.NullPointerException: Can't pass null for argument 'pathString' in child() at com.google.firebase.database.DatabaseReference.child(Unknown Source:40) at com.example.meenvandi.Signup$1.onClick(Signup.java:78) at android.view.View.performClick(View.java:6330) at android.view.View$PerformClick.run(View.java:25136) at android.os.Handler.handleCallback(Handler.java:790) at android.os.Handler.dispatchMessage(Handler.java:99) at android.os.Looper.loop(Looper.java:192) at android.app.ActivityThread.main(ActivityThread.java:6778) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:875)

I am just starting android and this project is very very impotent for me please help if i you can identify the problem which i am unable to

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
  • Check the value of `mobile` before you pass it to `child()`. – Doug Stevenson Mar 15 '19 at 17:25
  • in which activity ? @DougStevenson – Manu Thomas Mar 15 '19 at 17:29
  • Based on the stack trace given, you have a passed a `null` value to a reference's `child()` function. The call is in your signup button's `OnClickListener()` in the `Signup` activity. Because of `Unknown Source:40`, the null value is possibly referenced on line 40 of this handler. In the code above, this line is blank (it's just below `userData.put("City", city);`). When you uploaded this question, did you redact this line? If so, you'll have to sort this out yourself. You can learn how to read a stack trace [here](https://stackoverflow.com/questions/3988788) – samthecodingman Mar 17 '19 at 06:29

1 Answers1

0

One of the variables are null, its either mobile or uid, you can try to print both variables out to know which one is null.

My guess is you are trying to save a user in the db and this user haven't logged in to firebase before so uid will be null

Okeme Christian
  • 312
  • 3
  • 11
  • Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackoverflow.com/rooms/190134/discussion-on-answer-by-okeme-christian-cant-pass-null-for-argument-pathstring). – Samuel Liew Mar 16 '19 at 08:58