首页 > 解决方案 > 如何修复此错误:空对象引用上的“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 应用?

标签: androidfirebasefirebase-realtime-databasefirebase-authentication

解决方案


在这里,您需要首先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
}

推荐阅读