问题描述
我写了一个用于登录,通过电子邮件和Google登录的代码,但Logcat出现了错误,所以我读了它,这是由于我的代码中初始化过晚造成的,我尝试在溢出中搜索pproblem,但没有找到任何东西
kotlin.UninitializedPropertyAccessException:lateinit属性auth尚未初始化 原因:kotlin.UninitializedPropertyAccessException:lateinit属性auth尚未初始化 在com.example.preludeprototpe.Activity3Kt.access $ getAuth $ p(Activity3.kt:1) 在com.example.preludeprototpe.Activity3.checkLoggedInState(Activity3.kt:96) 在com.example.preludeprototpe.Activity3.onStart(Activity3.kt:48) 在android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1339) 在android.app.Activity.performStart(Activity.java:7167) 在android.app.ActivityThread.performlaunchActivity(ActivityThread.java:2895)
'''
class Activity3 : AppCompatActivity() {
lateinit var auth: FirebaseAuth
private val REQUEST_CODE_SIGN_IN = 0
private val _tag = "Activity3"
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity3)
btnlogin2activ3google.setonClickListener {
val option = GoogleSignInoptions.Builder(GoogleSignInoptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.cliendId))
.requestemail()
.build()
val sigInClient = GoogleSignIn.getClient(this,option)
sigInClient.signInIntent.also {
startActivityForResult(it,REQUEST_CODE_SIGN_IN)
}
}
btnloginactiv3.setonClickListener {
loginaccount()
}
}
override fun onStart() {
super.onStart()
checkLoggedInState()
}
override fun onActivityResult(requestCode: Int,resultCode: Int,data: Intent?) {
super.onActivityResult(requestCode,resultCode,data)
if (requestCode == REQUEST_CODE_SIGN_IN) {
val account = GoogleSignIn.getSignedInAccountFromIntent(data).result
account?.let {
googleaAuthForFirebase(it)
}
}
}
private fun googleaAuthForFirebase(account: GoogleSignInAccount) {
val credential = GoogleAuthProvider.getCredential(account.idToken,null)
Coroutinescope(dispatchers.IO).launch {
try {
auth.signInWithCredential(credential).await()
withContext(dispatchers.Main) {
Toast.makeText(this@Activity3,"Success login",Toast.LENGTH_LONG).show()
}
}catch (e: Exception){
withContext(dispatchers.Main) {
Toast.makeText(this@Activity3,e.message,Toast.LENGTH_LONG).show()
}
}
}
}
private fun loginaccount() {
val email = etemail.text.toString()
val password = etpassword.text.toString()
if(email.isNotEmpty() && password.isNotEmpty()){
Coroutinescope(dispatchers.IO).launch {
try {
auth.signInWithEmailAndPassword(email,password).await()
withContext(dispatchers.Main){
checkLoggedInState()
Log.d(_tag,"Activity3")
}
}catch (e:Exception){
withContext(dispatchers.Main){
Toast.makeText(this@Activity3,Toast.LENGTH_LONG).show()
}
}
}
}
}
private fun checkLoggedInState(){
if(auth.currentUser == null){
tvLoggedIn.text = getString(R.string.loggedin)
}else{
tvLoggedIn.text = getString(R.string.loggedin2)
}
}
}
解决方法
您尚未初始化变量。在onCreate中将其初始化,添加此代码
auth = FirebaseAuth.getInstance()