I am a beginner in android development and am making a pretty simple Login-Signup app that first logs in the users with email and password and then goes on to Phone authentication to verify their phone number via OTP. Now I found that Firebase provides different user ids to the Email/password authentication and Phone authentication. But I need them both to be under one userid so that they can login their account through email or phone number.
I did read various answers and official Firebase documentation on how to link multiple auth providers using linkWithCredential and tried to implement it in my code but it always fails showing error that this email is already in use by another account.
I couldn’t follow where I need to place the linkWithCredential method.
Please guide me, I am attaching the code for the two activities.
1)LoginActivity
package com.example.bccl
import android.content.ContentValues.TAG
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import android.os.Handler
import android.os.Looper
import android.text.InputType
import android.util.Log
import androidx.core.view.WindowInsetsCompat
import com.example.bccl.databinding.ActivityLoginBinding
import com.google.firebase.FirebaseException
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.PhoneAuthCredential
import com.google.firebase.auth.PhoneAuthOptions
import com.google.firebase.auth.PhoneAuthProvider
import com.google.firebase.auth.ktx.auth
import com.google.firebase.firestore.ktx.firestore
import com.google.firebase.ktx.Firebase
import java.util.concurrent.TimeUnit
class LoginActivity : AppCompatActivity() {
private val binding: ActivityLoginBinding by lazy {
ActivityLoginBinding.inflate(layoutInflater)
}
private lateinit var auth: FirebaseAuth
private var passwordShowing = false
private val db = Firebase.firestore
override fun onStart() {
super.onStart()
val currentUser = auth.currentUser
currentUser?.let {
Log.d(TAG,"user id is ${currentUser.uid}")
db.collection("user").document(currentUser.uid)
.get()
.addOnSuccessListener {
if (it != null && it.data?.get("otpverified") == true) {
val intent = Intent(this, MainActivity::class.java)
startActivity(intent)
finish()
}
}
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
setContentView(binding.root)
auth = Firebase.auth
binding.eyepassword2.setOnClickListener {
passwordShowing = !passwordShowing
if (passwordShowing) {
binding.editTextTextPassword.inputType = InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
binding.eyepassword2.setImageResource(R.drawable.eye)
} else {
binding.editTextTextPassword.inputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_PASSWORD
binding.eyepassword2.setImageResource(R.drawable.eye_off)
}
binding.editTextTextPassword.setSelection(binding.editTextTextPassword.text.length)
}
binding.SignUpText.setOnClickListener {
val intent = Intent(this, SignUp::class.java)
startActivity(intent)
finish()
}
val currentUser = auth.currentUser
if (currentUser != null) {
Log.d(TAG,"user id is ${currentUser.uid}")
}
binding.loginbutton.setOnClickListener {
val email = binding.editTextTextEmailAddress.text.toString().trim()
val password = binding.editTextTextPassword.text.toString().trim()
if (email.isBlank() || password.isBlank()) {
Toast.makeText(this, "Please Fill In All The Details", Toast.LENGTH_LONG).show()
} else if (!android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
Toast.makeText(this, "Please Enter a Valid Email", Toast.LENGTH_LONG).show()
} else {
binding.progressBar.visibility = View.VISIBLE
binding.loginbutton.visibility = View.INVISIBLE
binding.loginbutton.isEnabled = false
auth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(this) { task ->
binding.progressBar.visibility = View.GONE
binding.loginbutton.visibility = View.VISIBLE
binding.loginbutton.isEnabled = true
if (task.isSuccessful) {
Log.d(TAG, "signInWithEmail:success")
val intent = Intent(this, OTPVerificationActivity::class.java)
val userId = auth.currentUser?.uid
userId?.let {
val ref = db.collection("user").document(it)
ref.get()
.addOnSuccessListener { document ->
if (document != null) {
val phoneNumber = document.data?.get("phone").toString()
val options = PhoneAuthOptions.newBuilder(auth)
.setPhoneNumber("+91$phoneNumber")
.setTimeout(60L, TimeUnit.SECONDS)
.setActivity(this)
.setCallbacks(object : PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
override fun onVerificationCompleted(credential: PhoneAuthCredential) {
// Handle verification completion
}
override fun onVerificationFailed(e: FirebaseException) {
Toast.makeText(
this@LoginActivity,
e.message,
Toast.LENGTH_SHORT
).show()
}
override fun onCodeSent(
verificationId: String,
token: PhoneAuthProvider.ForceResendingToken
) {
intent.putExtra("verificationId", verificationId)
startActivity(intent)
finish()
}
override fun onCodeAutoRetrievalTimeOut(verificationId: String) {
// Handle code auto-retrieval timeout
}
})
.build()
PhoneAuthProvider.verifyPhoneNumber(options)
}
}
}
} else {
Log.w(TAG, "signInWithEmail:failure", task.exception)
Toast.makeText(baseContext, "Invalid Credentials.", Toast.LENGTH_SHORT).show()
}
}
}
}
ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
insets
}
}
}
- OTPVerification Activity
package com.example.bccl
import android.content.ContentValues.TAG
import android.content.Intent
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.util.Log
import android.view.View
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.example.bccl.databinding.ActivityOtpverificationBinding
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.FirebaseAuthInvalidCredentialsException
import com.google.firebase.auth.PhoneAuthCredential
import com.google.firebase.auth.PhoneAuthProvider
import com.google.firebase.auth.ktx.auth
import com.google.firebase.firestore.ktx.firestore
import com.google.firebase.ktx.Firebase
class OTPVerificationActivity : AppCompatActivity() {
private val binding: ActivityOtpverificationBinding by lazy {
ActivityOtpverificationBinding.inflate(layoutInflater)
}
private val db = Firebase.firestore
private val auth = Firebase.auth
private var realuser: String? = null
private var hero : String? = null
override fun onStart() {
super.onStart()
Log.d(TAG,"onStart() method")
hero = auth.currentUser?.uid
if (hero != null) {
Log.d(TAG, "User ID :$hero")
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
setContentView(binding.root)
fetchPhoneNumber()
val otpbackend = intent.getStringExtra("verificationId")
binding.verifybutton.setOnClickListener {
Log.d(TAG,"User ID :" + auth.currentUser?.uid)
realuser= auth.currentUser?.uid
verifyOtp(otpbackend)
}
ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
insets
}
setupOtpInputs()
}
private fun fetchPhoneNumber() {
val userId = FirebaseAuth.getInstance().currentUser?.uid
userId?.let { uid ->
val ref = db.collection("user").document(uid)
ref.get()
.addOnSuccessListener {
it?.data?.get("phone")?.toString()?.let { phoneNumber ->
binding.phnnumber.text = String.format("+91-%s", phoneNumber)
Toast.makeText(this, "Phone Number Fetched Successfully", Toast.LENGTH_SHORT).show()
Log.d("Firebase", "DocumentSnapshot data: ${it.data}")
}
}
.addOnFailureListener { exception ->
Log.e("Firebase", "Error fetching phone number", exception)
}
}
}
private fun verifyOtp(otpbackend: String?) {
val otp = binding.editTextText1.text.toString() +
binding.editTextText2.text.toString() +
binding.editTextText3.text.toString() +
binding.editTextText4.text.toString() +
binding.editTextText5.text.toString() +
binding.editTextText6.text.toString()
if (otp.length != 6) {
Toast.makeText(this, "Please Enter OTP", Toast.LENGTH_SHORT).show()
return
}
if (otpbackend == null) {
Toast.makeText(this, "Please Check Internet Connection", Toast.LENGTH_SHORT).show()
return
}
binding.progressBar.visibility = View.VISIBLE
binding.verifybutton.visibility = View.GONE
val credential = PhoneAuthProvider.getCredential(otpbackend, otp)
auth.currentUser?.let { currentUser ->
currentUser.linkWithCredential(credential)
.addOnCompleteListener(this) { task ->
binding.progressBar.visibility = View.GONE
binding.verifybutton.visibility = View.VISIBLE
if (task.isSuccessful) {
Log.d(TAG, "linkWithCredential:success")
} else {
Log.w(TAG, "linkWithCredential:failure", task.exception)
if (task.exception is FirebaseAuthInvalidCredentialsException) {
Toast.makeText(this, "Invalid OTP.", Toast.LENGTH_SHORT).show()
} else {
Toast.makeText(this, "Log-in failed.", Toast.LENGTH_SHORT).show()
}
}
}
signInWithPhoneAuthCredential(credential)
}
}
private fun signInWithPhoneAuthCredential(credential: PhoneAuthCredential) {
auth.signInWithCredential(credential)
.addOnCompleteListener(this) { task ->
binding.progressBar.visibility = View.GONE
binding.verifybutton.visibility = View.VISIBLE
if (task.isSuccessful) {
Log.d(TAG, "signInWithCredential:success, user id : ${auth.currentUser?.uid}")
val currentUser = auth.currentUser
if (currentUser != null) {
markOTPVerification(currentUser.uid)
}
// Proceed to main activity
navigateToMainActivity()
} else {
Log.w(TAG, "signInWithCredential:failure", task.exception)
if (task.exception is FirebaseAuthInvalidCredentialsException) {
Toast.makeText(this, "Invalid OTP.", Toast.LENGTH_SHORT).show()
} else {
Toast.makeText(this, "Log-in failed.", Toast.LENGTH_SHORT).show()
}
}
}
}
private fun navigateToMainActivity() {
val intent = Intent(this, MainActivity::class.java)
intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
startActivity(intent)
finish()
}
private fun markOTPVerification(uid: String) {
db.collection("user").document(uid)
.update("otpverified", true)
.addOnSuccessListener {
Log.d(TAG, "OTP Verification marked in database successfully")
}
.addOnFailureListener { e ->
Log.w(TAG, "Error marking OTP Verification", e)
Toast.makeText(this, "Failed to mark OTP Verification", Toast.LENGTH_SHORT).show()
}
}
private fun setupOtpInputs() {
val textWatcher = object : TextWatcher {
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
if (s?.length == 1) {
when (currentFocus?.id) {
R.id.editTextText1 -> binding.editTextText2.requestFocus()
R.id.editTextText2 -> binding.editTextText3.requestFocus()
R.id.editTextText3 -> binding.editTextText4.requestFocus()
R.id.editTextText4 -> binding.editTextText5.requestFocus()
R.id.editTextText5 -> binding.editTextText6.requestFocus()
}
}
}
override fun afterTextChanged(s: Editable?) {}
}
binding.editTextText1.addTextChangedListener(textWatcher)
binding.editTextText2.addTextChangedListener(textWatcher)
binding.editTextText3.addTextChangedListener(textWatcher)
binding.editTextText4.addTextChangedListener(textWatcher)
binding.editTextText5.addTextChangedListener(textWatcher)
binding.editTextText6.addTextChangedListener(textWatcher)
}
}
Sourav_039_CSE is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.