2

I am trying to create a phone number logging section in my application so that the user can log in using the phone number. I am trying to run my application on the physical device when I try to login using the phone number and received an error says the null reference. I have searched for the solution all over the internet but didn't get any proper solution to remove this error. I have allowed the phone authentication in firebase still, I am getting the error. I have used the country picker in my activity to get the country code and it works file.

Error occurs in

     PhoneAuthProvider.getInstance().verifyPhoneNumber(
                phonestring,
                60,
                TimeUnit.SECONDS,
                Phoneactivity.this,
                mCallbacks
        );

Phoneactivity.java

    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_phoneactivity);

    mAuth = FirebaseAuth.getInstance();

    initalization();
    phonenumbermethod();
    emailloginmethod();
}

private void emailloginmethod() {
    emaillogin.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(getApplicationContext(),Loginactivity.class);
            startActivity(intent);
        }
    });
}

private void phonenumbermethod() {
    if(REQUEST.equals("phone")){
        submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                REQUEST = "OTP";
                String phonenumberstring = phone.getText().toString();
                String countrycode = ccp.getSelectedCountryCodeWithPlus();
                phonestring = countrycode + phonenumberstring;
                //Toast.makeText(getApplicationContext(),phonestring,Toast.LENGTH_SHORT).show();
                verificationcodesend();
            }
        });
    }else{
        submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                REQUEST = "phone";
                otpstring = otp.getText().toString();
                otpmethod();
            }
        });
    }
}

private void otpmethod() {
    if (TextUtils.isEmpty(otpstring)){
        Toast.makeText(getApplicationContext(),"Please enter the verification code", Toast.LENGTH_SHORT).show();
    }else{
        loadingBar.setTitle("Verification code");
        loadingBar.setMessage("Please wait...");
        loadingBar.setCanceledOnTouchOutside(false);
        loadingBar.show();
        PhoneAuthCredential credential = PhoneAuthProvider.getCredential(mVerificationId, otpstring);
        signInWithPhoneAuthCredential(credential);
    }
}

private void verificationcodesend() {
    if(TextUtils.isEmpty(phonestring)){
        Toast.makeText(getApplicationContext(),"Please enter phone number",Toast.LENGTH_SHORT).show();
    }else{
        loadingBar.setTitle("Phone verification");
        loadingBar.setMessage("Please wait till we verify your account");
        loadingBar.setCanceledOnTouchOutside(false);
        loadingBar.show();
        Log.i("phoneactivity",phonestring);
        PhoneAuthProvider.getInstance().verifyPhoneNumber(
                phonestring,
                60,
                TimeUnit.SECONDS,
                Phoneactivity.this,
                mCallbacks
        );
    }
    mCallbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
        @Override
        public void onVerificationCompleted(@NonNull PhoneAuthCredential phoneAuthCredential) {
            signInWithPhoneAuthCredential(phoneAuthCredential);
        }

        @Override
        public void onVerificationFailed(@NonNull FirebaseException e) {
            loadingBar.dismiss();
            Toast.makeText(getApplicationContext(),"Please enter the correct phone number", Toast.LENGTH_SHORT).show();

        }

        @Override
        public void onCodeSent(@NonNull String verificationId,
                               @NonNull PhoneAuthProvider.ForceResendingToken token) {
            loadingBar.dismiss();

            mVerificationId = verificationId;
            mResendToken = token;
            Toast.makeText(getApplicationContext(),"Verification code has been send", Toast.LENGTH_SHORT).show();
            otpnumber.setVisibility(View.VISIBLE);
            phonenumber.setVisibility(View.GONE);
        }
    };
}
private void signInWithPhoneAuthCredential(PhoneAuthCredential credential) {
    mAuth.signInWithCredential(credential)
            .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                    if (task.isSuccessful()) {
                        loadingBar.dismiss();
                        sendusertomainActivity();
                        Toast.makeText(getApplicationContext(),"welcome",Toast.LENGTH_SHORT).show();
                    } else {
                        String msg = task.getException().toString();
                        Toast.makeText(getApplicationContext(),"Error: "+ msg, Toast.LENGTH_SHORT).show();
                    }
                }
            });
}

private void sendusertomainActivity() {
    Intent intent = new Intent(getApplicationContext(),HomeActivity.class);
    startActivity(intent);
}

error: null reference

      java.lang.NullPointerException: null reference
    at com.google.android.gms.common.internal.Preconditions.checkNotNull(Unknown Source:2)
    at com.google.firebase.auth.PhoneAuthProvider.verifyPhoneNumber(com.google.firebase:firebase-auth@@19.2.0:9)
    at com.nanb.Alpha.Phoneactivity.verificationcodesend(Phoneactivity.java:109)
    at com.nanb.Alpha.Phoneactivity.access$300(Phoneactivity.java:28)
    at com.nanb.Alpha.Phoneactivity$2.onClick(Phoneactivity.java:72)
    at android.view.View.performClick(View.java:6608)
    at android.view.View.performClickInternal(View.java:6585)
    at android.view.View.access$3100(View.java:785)
    at android.view.View$PerformClick.run(View.java:25921)
    at android.os.Handler.handleCallback(Handler.java:873)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:201)
    at android.app.ActivityThread.main(ActivityThread.java:6864)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:873)

update

  2020-03-15 21:03:00.382 30384-30384/com.nanb.Alpha I/phoneactivity: +919771553694
NANB
  • 35
  • 4
  • If though your code checks against it, it seems that `phonestring` is empty. You might want to log it just before calling Firebase, and see if it meets the requirements: https://firebase.google.com/docs/reference/android/com/google/firebase/auth/PhoneAuthProvider#verifyPhoneNumber(java.lang.String,%20long,%20java.util.concurrent.TimeUnit,%20android.app.Activity,%20com.google.firebase.auth.PhoneAuthProvider.OnVerificationStateChangedCallbacks) – Frank van Puffelen Mar 15 '20 at 14:36
  • phonestring is not empty as when i toast the string it shows the number – NANB Mar 15 '20 at 14:52
  • 1) Instead of toasting it (which we can't see), `Log.i` it in your code, and then include both that updated code and its output in your question. That way we're all be looking at the same code and output. 2) I don't necessarily think the number is empty/null, but I do wonder if it has some other unusual value that upsets the SDK. – Frank van Puffelen Mar 15 '20 at 15:29
  • 1
    I have added the log.i and updated the code – NANB Mar 15 '20 at 15:36
  • Thanks that is really helpful. In the end I went back to the source code and realized that `Preconditions.checkNotNull` doesn't happen on the phone number, but only on other arguments. See my answer below. In general, whenever you get a null pointer exception, run the code in a debugger, and see what argument is `null` when it breaks. See https://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it – Frank van Puffelen Mar 15 '20 at 15:56

1 Answers1

1

You're not initializing mCallback before passing it into verifyPhoneNumber, which is what the null check is complaining about.

To fix it, move the mCallbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {... before the call to verifyPhoneNumber.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807