How to change the Signed in Phone Number in Firebase Authentication for Android?

12,696

Solution 1

An API exists for updating the phone number of a current user: FirebaseUser#updatePhoneNumber(PhoneAuthCredential credential)

Solution 2

    val options = PhoneAuthOptions.newBuilder(FirebaseAuth.getInstance())
            .setPhoneNumber(phoneNumber) // Phone number to verify
            .setTimeout(100L, TimeUnit.SECONDS) // Timeout and unit
            .setActivity(activity) // Activity (for callback binding)
            .setCallbacks(returnCallBack()) // OnVerificationStateChangedCallbacks
            .build()

 PhoneAuthProvider.verifyPhoneNumber(options)

private fun returnCallBack() = object : PhoneAuthProvider
    .OnVerificationStateChangedCallbacks() {

        override fun onVerificationCompleted(credential: PhoneAuthCredential) {
            FirebaseAuth.getCurrentUser()?.updatePhoneNumber(credential)
        }

        override fun onVerificationFailed(e: FirebaseException) {
            // This callback is invoked in an invalid request for verification is made,
            // for instance if the the phone number format is not valid.
            Log.e("phone",  e.toString())

        }

        override fun onCodeSent(verificationId: String, token: PhoneAuthProvider.ForceResendingToken) {
            //You need this to pass as a parameter for the update method call.
            vericationSent = verificationId
        }
    }   

 fun confirmChange(code: String, context: Context?) {
        if(code.contains(Regex(onlyNumber))) {
            Log.d("codeSent" , "Right code : $code")

            FirebaseAuth.getCurrentUser()
                ?.updatePhoneNumber(PhoneAuthProvider.getCredential(vericationSent, code))
                ?.addOnCompleteListener {task ->
                    //it worked if you reach here.

                }?.addOnFailureListener {
                    //Show the error to user
                    }
                }

            vericationSent = EMPTY
        } else {
            Log.d("codeSent" , "wrong code : $code")
        }

    }

Solution 3

I also had this challenge to update user phone number and when I go on documentation I got something by using I have done this task.

you can go for documentation by click here

Now the method you can use : - for java android project.

PhoneAuthCredential phoneAuthCredential = PhoneAuthProvider.getCredential( "+91-98298XXXX2", "OTP_CODE" );
// Update Mobile Number...
firebaseAuth.getCurrentUser().updatePhoneNumber(phoneAuthCredential)
    .addOnCompleteListener(new OnCompleteListener <Void>() {
        @Override
        public void onComplete(@NonNull Task <Void> task) {
            if (task.isSuccessful()) {
                // Update Successfully
            } else {
                // Failed
            }
        }
    }
);

Solution 4

Try this

//Send otp to phone number

String verificationId;
private void startLoginFirebase(){
    PhoneAuthProvider.getInstance(firebaseAuth).verifyPhoneNumber(phone, 90L, TimeUnit.SECONDS, PhoneAuthActivity.this, new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
        @Override
        public void onCodeSent(@NonNull String s, @NonNull PhoneAuthProvider.ForceResendingToken forceResendingToken) {
            super.onCodeSent(s, forceResendingToken);
            verificationId = s;
            updatePhoneNum();
        }

        @Override
        public void onCodeAutoRetrievalTimeOut(@NonNull String s) {
            super.onCodeAutoRetrievalTimeOut(s);
        }

        @Override
        public void onVerificationCompleted(@NonNull PhoneAuthCredential phoneAuthCredential) {

        }

        @Override
        public void onVerificationFailed(@NonNull FirebaseException e) {
            processFurther(e.getLocalizedMessage().toString(), 0);
        }
    });
}


//Verify Otp

private void updatePhoneNum(){
    PhoneAuthCredential phoneAuthCredential = PhoneAuthProvider.getCredential(verificationId, otp);
    firebaseAuth.getCurrentUser().updatePhoneNumber(phoneAuthCredential).addOnCompleteListener(new OnCompleteListener<Void>() {
        @Override
        public void onComplete(@NonNull Task<Void> task) {

        }
    });
}
Share:
12,696
Nithin
Author by

Nithin

Updated on June 03, 2022

Comments

  • Nithin
    Nithin about 2 years

    I am using Android Firebase Auth Ui for providing Phone Number based sign in option in an android app. I am trying to provide an additional option to signed in users to switch their signed in phone number to another number keeping the same user account.

    But as per Firebase Docs for Phone number there are no options to change the signed in number.

    There are options for linking different auth providers like email, google or Facebook login etc to same account. But there is no way mentioned about how to change the phone number or email id keeping the same user id.

    Is there a workaround or method by which we can achieve this?

  • Pratik Butani
    Pratik Butani almost 6 years
    You must have to give an short example.
  • loekTheDreamer
    loekTheDreamer over 4 years
    @PratikButani i also dont understand why the doc doesnt reflect how the code looks or works. its so abstract i dont understand it either.
  • MaxV
    MaxV over 3 years
    Hi TheSeeKer. Thanks for your answer. Usually answers with an explanation are more welcomed there. Would you like to add an explanation to your answer?
  • TheSeeKer
    TheSeeKer over 3 years
    Hi MaxV, Make this call "PhoneAuthProvider.verifyPhoneNumber(options)" using the new phone number ( while building options object) from you old phone device where you have you app (with Firebase Auth). Then once you receive the code from the device you want to start using, take this code use it with the verificationId you receive from onCodeSent callback to make this following call "FirebaseAuth.getCurrentUser() ?.updatePhoneNumber(PhoneAuthProvider.getCredential(vericati‌​onSent, code))". That's about it.