How to link the user id of Phone authentication with user id of email password authentication in Firebase (Android Studio)

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
        }
    }
}
  1. 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)
    }
}

New contributor

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.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật