java.lang.RuntimeException:无法启动活动 ComponentInfoat.mksquad.swapit/at.mksquad.swapit.ui.screenflow.mai

Posted

技术标签:

【中文标题】java.lang.RuntimeException:无法启动活动 ComponentInfoat.mksquad.swapit/at.mksquad.swapit.ui.screenflow.main.MainActivity?【英文标题】:java.lang.RuntimeException: Unable to start activity ComponentInfoat.mksquad.swapit/at.mksquad.swapit.ui.screenflow.main.MainActivity?java.lang.RuntimeException:无法启动活动 ComponentInfoat.mksquad.swapit/at.mksquad.swapit.ui.screenflow.main.MainActivity? 【发布时间】:2021-11-04 03:16:47 【问题描述】:

我正在开发新的应用程序,但是当我在调试模式下运行项目时出现以下异常

java.lang.RuntimeException: Unable to start activity ComponentInfoat.mksquad.swapit/at.mksquad.swapit.ui.screenflow.main.MainActivity: java.lang.NullPointerException
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2976)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3113)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:113)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:71)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1858)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:201)
        at android.app.ActivityThread.main(ActivityThread.java:6820)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:922)
     Caused by: java.lang.NullPointerException
        at at.mksquad.swapit.data.sources.auth.AuthSourceFirebase.getUidOfLoggedInUser(AuthSourceFirebase.kt:18)
        at at.mksquad.swapit.features.auth.AuthManager.getUidOfLoggedInUser(AuthManager.kt:28)
        at at.mksquad.swapit.data.repositories.UserRepository.getUid(UserRepository.kt:30)
        at at.mksquad.swapit.utils.UserUtil.createNewUser(UserUtil.kt:17)
        at at.mksquad.swapit.data.repositories.UserRepository.loadUser(UserRepository.kt:90)
        at at.mksquad.swapit.ui.screenflow.main.SharedViewModel.<init>(SharedViewModel.kt:12)
        at at.mksquad.swapit.ui.screenflow.main.SharedViewModelFactory.create(SharedViewModelFactory.kt:14)
        at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:187)
        at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:150)
        at androidx.lifecycle.ViewModelLazy.getValue(ViewModelProvider.kt:54)
        at androidx.lifecycle.ViewModelLazy.getValue(ViewModelProvider.kt:41)
        at at.mksquad.swapit.ui.screenflow.main.MainActivity.getSharedViewModel(Unknown Source:2)
        at at.mksquad.swapit.ui.screenflow.main.MainActivity.prepareViews(MainActivity.kt:765)
        at at.mksquad.swapit.ui.screenflow.main.MainActivity.onCreate(MainActivity.kt:194)
        at android.app.Activity.performCreate(Activity.java:7224)


        at android.app.Activity.performCreate(Activity.java:7213)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1272)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2956)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3113) 
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78) 
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:113) 
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:71) 
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1858) 
        at android.os.Handler.dispatchMessage(Handler.java:106) 
        at android.os.Looper.loop(Looper.java:201) 
        at android.app.ActivityThread.main(ActivityThread.java:6820) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:922) 

下面跟随 My MainActivity.kt https://gist.github.com/kyodgorbek/2a369fcbb2138cb9e25c0855514dc162 代码

我想知道我到底在哪里犯了错误我已经运行调试模式但逐步运行但它没有显示任何内容,但在 AuthSourceFirebase.kt 中的以下代码中指出异常

object AuthSourceFirebase 
    fun isUserLoggedIn(): Boolean 
        return FirebaseAuth.getInstance().currentUser != null
    

    fun getUidOfLoggedInUser(): String 
        return FirebaseAuth.getInstance().currentUser!!.uid // this line cause exception
    

    fun loginUser(
        activity: Activity,
        mail: String,
        password: String,
        loginCallback: AuthManager.UserLoginCallback
    ) 
        Timber.d("Starting process to login..")
        FirebaseAuth.getInstance().signInWithEmailAndPassword(
            mail,
            password
        ).addOnCompleteListener(activity) 
            if (it.isSuccessful) 
                loginCallback.onCallback(null)
            
        
            .addOnFailureListener  e ->
                val error = e as FirebaseAuthException
                Timber.d("Error logging in, code: %s", error.errorCode)
                loginCallback.onCallback(
                    LibFirebaseErrors.getErrorFromErrorCode(
                        activity,
                        error.errorCode
                    )
                )
            
    

    fun registerUser(
        activity: Activity,
        mail: String,
        password: String,
        registrationCallback: AuthManager.UserRegistrationCallback
    ) 
        Timber.d("Starting process to register..")
        FirebaseAuth.getInstance().createUserWithEmailAndPassword(
            mail,
            password
        ).addOnCompleteListener(activity) 
            if (it.isSuccessful) 
                registrationCallback.onCallback(null)
            
        
            .addOnFailureListener  e ->
                val error = e as FirebaseAuthException
                Timber.d("Error logging in, code: %s", error.errorCode)
                registrationCallback.onCallback(
                    LibFirebaseErrors.getErrorFromErrorCode(activity, error.errorCode)
                )
            
    

    fun sendPasswordResetMail(
        activity: Activity,
        mail: String,
        resetPwMailCallback: AuthManager.UserResetPwMailCallback
    ) 
        Timber.d("Starting process to reset password..")
        FirebaseAuth.getInstance().sendPasswordResetEmail(mail)
            .addOnCompleteListener(activity) 
                if (it.isSuccessful) 
                    resetPwMailCallback.onCallback(null)
                
            
            .addOnFailureListener  e ->
                val error = e as FirebaseAuthException
                Timber.d("Error sending mail, code: %s", error.errorCode)
                resetPwMailCallback.onCallback(
                    LibFirebaseErrors.getErrorFromErrorCode(
                        activity,
                        error.errorCode
                    )
                )
            
    

    fun logUserOut(context: Context)
        UserRepository.deleteUserLocal(context)
        FirebaseAuth.getInstance().signOut()
    

我已经尝试过我的方法以避免空指针异常,因为它不起作用

fun getUidOfLoggedInUser(): String 

        if(FirebaseAuth.getInstance().currentUser?.uid == null)
            FirebaseAuth.getInstance().signOut()
        
        return FirebaseAuth.getInstance().currentUser!!.uid
    

【问题讨论】:

【参考方案1】:

您得到的错误看起来像一个常规的空指针异常。根据这里的异常堆栈跟踪:

Caused by: java.lang.NullPointerException
    at at.mksquad.swapit.data.sources.auth.AuthSourceFirebase.**getUidOfLoggedInUser(AuthSourceFirebase.kt:18)**
    at at.mksquad.swapit.features.auth.AuthManager.getUidOfLoggedInUser(AuthManager.kt:28)
    at at.mksquad.swapit.data.repositories.UserRepository.getUid(UserRepository.kt:30)

fun getUidOfLoggedInUser(): String 
    return FirebaseAuth.getInstance().currentUser!!.uid // this line cause exception

确保您的 currentUser 不为空。请检查 Firebase 身份验证是否已处理且当前用户会话是否处于活动状态。

像这样更新你的代码:

**fun getUidOfLoggedInUser(): String 

    if(FirebaseAuth.getInstance().currentUser == null || FirebaseAuth.getInstance().currentUser?.uid == null)
        FirebaseAuth.getInstance().signOut() return
    
    return FirebaseAuth.getInstance().currentUser!!.uid
**

【讨论】:

我已经更改了其他代码,例如这个有趣的 getUidOfLoggedInUser(): String? return FirebaseAuth.getInstance().currentUser.uid // 但我已经在多个地方更改了代码实现你的建议是什么 如何在实际代码中实现以下功能确保您的 currentUser 不为空。请检查 Firebase 身份验证是否已处理且当前用户会话是否处于活动状态。你能解释一下你在编码示例中所说的内容吗 @sashabeliy !!表示 currentUser 不能为 null,如果 currentUser 为 null,请将 currentUser!!.uid 更改为 currentUser?.uid 并将用户路由到登录屏幕进行身份验证。 请检查我已经按照你说的那样实现的更新代码,或者请重新编辑你的代码

以上是关于java.lang.RuntimeException:无法启动活动 ComponentInfoat.mksquad.swapit/at.mksquad.swapit.ui.screenflow.mai的主要内容,如果未能解决你的问题,请参考以下文章

Android Studio 按钮导致崩溃

添加 ImageView 时应用程序崩溃?