android - 如何修复此错误:空对象引用上的“java.lang.Class java.lang.Object.getClass()”
问题描述
我正在制作一个 Android 聊天应用程序。用户,如果验证并登录,则通过执行以下代码超越 StartActivity。
@Override
protected void onStart() {
super.onStart();
auth = FirebaseAuth.getInstance();
firebaseUser = auth.getCurrentUser();
//redirect if user is not null
if (Objects.requireNonNull(auth.getCurrentUser()).isEmailVerified()) {
if (firebaseUser != null) {
startActivity(new Intent(StartActivity.this, HomeActivity.class));
finish();
}
} else {
startActivity(new Intent(StartActivity.this, LoginActivity.class));
Toast.makeText(this, "Verify your email id!", Toast.LENGTH_SHORT).show();
}
}
但是每当我运行该应用程序时,它会突然关闭并向我显示此错误。
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Class java.lang.Object.getClass()' on a null object reference
at com.smproductions.flingg.StartActivity.onStart(StartActivity.java:32)
at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1425)
at android.app.Activity.performStart(Activity.java:7825)
at android.app.ActivityThread.handleStartActivity(ActivityThread.java:3294)
at android.app.servertransaction.TransactionExecutor.performLifecycleSequence(TransactionExecutor.java:221)
at android.app.servertransaction.TransactionExecutor.cycleToPath(TransactionExecutor.java:201)
at android.app.servertransaction.TransactionExecutor.executeLifecycleState(TransactionExecutor.java:173)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:97)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2016)
at android.os.Handler.dispatchMessage(Handler.java:107)
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)
我该如何解决这个问题?
如需更多参考,请查看我的另一个问题,我在其中添加了更多可能有用的代码片段。 如果用户不先点击 Firebase 身份验证发送的验证链接,如何防止用户登录 Android 应用?
解决方案
在这里,您需要首先auth.getCurrentUser()
从您所说的评论中检查是否auth.getCurrentUser()
为 null,因为 null 这意味着没有用户登录。您可以在此处getCurrentUser()
了解有关该属性的更多信息。
所以在这里你应该首先检查当前用户firebaseUser
是否为空,所以代码应该是: -
//Check if the firebase user exist or not
if (firebaseUser != null) {
if (firebaseUser. isEmailVerified()) {
// Your user is verified and can navigate to home activity
} else {
// Your user is not verified
}
} else {
// You don't have a signed in user
}
推荐阅读
- python - 如何在不使用 python 内置的 max 和 min 函数的情况下将给定列表的最大值和最小值转换为元组形式
- tensorflow - 召回率、准确率、假阳性率和真阳性率都在不断地给出零值
- python - 如何将站点地图集成到 django-oscar?
- php - 将 $_POST 变量格式化为准备好的语句
- sql-server - SQL:将子查询转换为公用表表达式
- angular - 当用户点击选择元素的下拉菜单时如何显示更多数据?
- vue.js - Router Link 只更新活动类一次
- ibm-cloud-infrastructure - 如何在 Network Gateway vsrx 中先解除关联,然后再关联特定 VLAN
- asp.net - 访问控制:数据库强化问题
- jhipster - 在Tomcat下运行jHipster war文件