从我创建项目的时候起,这就工作得很好。但突然它开始崩溃。注册活动运行良好。但是这个信号正在崩溃。
调试器显示的错误。
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.durden, PID: 7921
java.lang.NullPointerException
at com.example.durden.activity.SignInActivity.onCreate$lambda-2(SignInActivity.kt:49)
at com.example.durden.activity.SignInActivity.$r8$lambda$ZBrxDCm4vr69l-PuE690AA_KCF8(Unknown Source:0)
at com.example.durden.activity.SignInActivity$$ExternalSyntheticLambda1.onClick(Unknown Source:4)
at android.view.View.performClick(View.java:7125)
at android.view.View.performClickInternal(View.java:7102)
at android.view.View.access$3500(View.java:801)
at android.view.View$PerformClick.run(View.java:27336)
at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7356)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
signin Activity
class SignInActivity : AppCompatActivity() {
// getting the references from firebase
private var auth: FirebaseAuth? = null
private var firebaseUser: FirebaseUser? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// gets the view binding of sign_in_activity
val binding = ActivitySignInBinding.inflate(layoutInflater)
setContentView(binding.root)
// ends this activity and goes to sign up page if needed
binding.gotoSignUp.setOnClickListener {
val intent = Intent(
this@SignInActivity,
SignUpActivity::class.java
)
startActivity(intent)
finish()
}
binding.btnSignIn.setOnClickListener {
// storing the entered email and password
val email = binding.SImail.text.toString()
val password = binding.SIpass.text.toString()
// checks if the values are entered
if (TextUtils.isEmpty(email) && TextUtils.isEmpty(password)) {
Toast.makeText(applicationContext,"email and password are required", Toast.LENGTH_SHORT).show()
}
// signs in the user using firebase data
else {
auth!!.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(this) {
if (it.isSuccessful) {
binding.SImail.setText("")
binding.SIpass.setText("")
// after sign in takes to user page
val intent = Intent(
this@SignInActivity,
UserActivity::class.java
)
startActivity(intent)
finish()
}
else {
Toast.makeText( applicationContext, "Invalid password or email", Toast.LENGTH_SHORT).show()
}
}
}
}
}
}
Firebase Authentication导致Android致命异常
这听起来和我的问题很相似,但是我还是不明白为什么会这样。
您从未初始化auth
,这意味着当您执行auth!!.signInWithEmailAndPassword(email, password)
时,您会得到一个异常。
在onCreate
中初始化auth
,如步骤2所示,以防止错误。
// Initialize Firebase Auth
auth = Firebase.auth
NullPointerException
是非常常见的,所以我强烈建议学习如何自己解决这些问题。请查看:
- 什么是Kotlin双bang(!! !)操作符? 不幸的是,MyApp已经停止了。我怎么解决这个问题?
- 什么是NullPointerException,我该如何修复它?
您对视图进行了两次充气,这是错误的:
val binding = ActivitySignInBinding.inflate(layoutInflater)
// setContentView(binding.root)