Reputation: 1470
I am using Firebase and I am trying to register users with phone auth.
here is my full activity code
class RegisterActivity : AppCompatActivity(){
private val auth = FirebaseAuth.getInstance()
private val timeoutSeconds = 60L
private lateinit var storedVerificationId: String
private lateinit var resendToken: PhoneAuthProvider.ForceResendingToken
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_register)
registerbtn.setOnClickListener { registerButtonClicked() }
verifybtn.setOnClickListener { verifyButtonClicked() }
}
fun registerButtonClicked() {
registerPhoneNumber(editTextPhone.text.toString())
}
private fun verifyButtonClicked() {
verifyUser(editTextPhone.text.toString())
}
private fun registerPhoneNumber(phoneNumber: String) {
val options = PhoneAuthOptions.newBuilder(auth)
.setPhoneNumber(phoneNumber)
.setTimeout(timeoutSeconds, TimeUnit.SECONDS)
.setActivity(activity)
.setCallbacks(callbacks)
.build()
PhoneAuthProvider.verifyPhoneNumber(options)
}
private val callbacks = object : PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
override fun onVerificationCompleted(credential: PhoneAuthCredential) {
signInWithPhoneAuthCredential(credential)
}
override fun onVerificationFailed(e: FirebaseException) {
}
override fun onCodeSent(
verificationId: String,
token: PhoneAuthProvider.ForceResendingToken
) {
storedVerificationId = verificationId
resendToken = token
}
}
private fun signInWithPhoneAuthCredential(credential: PhoneAuthCredential) {
auth.signInWithCredential(credential)
.addOnCompleteListener(activity) { task ->
if (task.isSuccessful) {
Log.d(TAG, "signInWithCredential:success")
}
}
}
fun verifyUser(verificationCode: String) {
val credential = PhoneAuthProvider.getCredential(storedVerificationId, verificationCode)
signInWithPhoneAuthCredential(credential)
}
I got an exception that storedVerificationId
was not set, even though I set it already in onCodeSent
What am I doing wrong here? and is the flow that I am following correct?
Upvotes: 0
Views: 331
Reputation: 317322
The Kotlin runtime is giving you this message because it saw that that storedVerificationId
was not given a non-null value before it's used in verifyUser
.
You will likely just want to remove the lateinit
keyword from it, and allow a null initial value. You will have to check for null to ensure it's set before you use it.
private var storedVerificationId: String? = null
fun verifyUser(verificationCode: String) {
if (storedVerificationId != null) {
val credential = PhoneAuthProvider.getCredential(storedVerificationId, verificationCode)
signInWithPhoneAuthCredential(credential)
}
else {
// decide what you want to do if it hasn't been given a value yet.
}
}
Upvotes: 1