Fragment not attached to Activity, How to solve?

184 Views Asked by At

I am using navigation component with bottom navigation view.

The issue is When I open the application the selected fragment is home fragment then when I navigate to another fragment(Favorite) and use the context everything is okay. but when I navigate to the home fragment and then navigate to favorite fragment when I use the context the app crashes and I get this illegalStateException : java.lang.IllegalStateException: Fragment Favorite{19d069d} (bfafcdd4-bba2-4005-9437-65c1d0a51977) not attached to Activity

This is the behavior

This is how I initialize the bottom nav with the navController

 val navHostFragment =
            supportFragmentManager.findFragmentById(R.id.mainFragmentContainer) as NavHostFragment
 navController = navHostFragment.navController

 setupWithNavController(binding.bottomNavigationView, navController)

and this is the nav file :

    <navigation xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/main_navigation"
    app:startDestination="@id/home">

    <fragment
        android:id="@+id/home"
        android:name="com.androdevelopment.wallpaper.view.home.Home"
        android:label="fragment_home"
        tools:layout="@layout/fragment_home">
        <action
            android:id="@+id/action_home_to_menu"
            app:destination="@id/menu" />
        <action
            android:id="@+id/action_home_to_favorite"
            app:destination="@id/favorite"
             />
    </fragment>
    <fragment
        android:id="@+id/favorite"
        android:name="com.androdevelopment.wallpaper.view.favorite.Favorite"
        android:label="fragment_favorite"
        tools:layout="@layout/fragment_favorite">
        <action
            android:id="@+id/action_favorite_to_home"
            app:destination="@id/home" />
        <action
            android:id="@+id/action_favorite_to_menu"
            app:destination="@id/menu"

            />
    </fragment>
    </navigation>

and the full log :

java.lang.IllegalStateException: Fragment Favorite{9fbcc19} (f8c928e4-bc35-4543-a26b-f917feb3a9df) not attached to Activity
    at androidx.fragment.app.Fragment.startActivity(Fragment.java:1446)
at androidx.fragment.app.Fragment.startActivity(Fragment.java:1436)
at com.androdevelopment.wallpaper.view.favorite.Favorite$collectUiEvents$1$1.emit(Favorite.kt:245)
at com.androdevelopment.wallpaper.view.favorite.Favorite$collectUiEvents$1$1.emit(Favorite.kt:235)
at kotlinx.coroutines.flow.FlowKt__ChannelsKt.emitAllImpl$FlowKt__ChannelsKt(Channels.kt:37)
at kotlinx.coroutines.flow.FlowKt__ChannelsKt.access$emitAllImpl$FlowKt__ChannelsKt(Channels.kt:1)
at kotlinx.coroutines.flow.FlowKt__ChannelsKt$emitAllImpl$1.invokeSuspend(Unknown Source:14)
at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
at kotlinx.coroutines.DispatchedTask.run(DispatchedTask.kt:108)
at kotlinx.coroutines.EventLoop.processUnconfinedEvent(EventLoop.common.kt:68)
atkotlinx.coroutines.internal.DispatchedContinuationKt.resumeCancellableWith(DispatchedContinuation.kt:375)
at kotlinx.coroutines.intrinsics.CancellableKt.startCoroutineCancellable(Cancellable.kt:30)
at kotlinx.coroutines.intrinsics.CancellableKt.startCoroutineCancellable$default(Cancellable.kt:25)
at kotlinx.coroutines.CoroutineStart.invoke(CoroutineStart.kt:110)
at kotlinx.coroutines.AbstractCoroutine.start(AbstractCoroutine.kt:126)
at kotlinx.coroutines.BuildersKt__Builders_commonKt.launch(Builders.common.kt:56)
at kotlinx.coroutines.BuildersKt.launch(Unknown Source:1)
at kotlinx.coroutines.BuildersKt__Builders_commonKt.launch$default(Builders.common.kt:47)
at kotlinx.coroutines.BuildersKt.launch$default(Unknown Source:1)
at com.androdevelopment.wallpaper.view.favorite.viewmodel.FavoritesViewModel.sendUiEvent(FavoritesViewModel.kt:97)
at com.androdevelopment.wallpaper.view.favorite.viewmodel.FavoritesViewModel.onEvent(FavoritesViewModel.kt:90)
at com.androdevelopment.wallpaper.view.favorite.Favorite$favoriteAdapter$2$1.onWallpaperClick(Favorite.kt:61)
at com.androdevelopment.wallpaper.view.favorite.adapter.FavoriteAdapter.onBindViewHolder$lambda$0(FavoriteAdapter.kt:48)
at com.androdevelopment.wallpaper.view.favorite.adapter.FavoriteAdapter.$r8$lambda$QHKf0dj1K1b9eNHLFJzLaOqv-q0(Unknown Source:0)
at com.androdevelopment.wallpaper.view.favorite.adapter.FavoriteAdapter$$ExternalSyntheticLambda0.onClick(Unknown Source:4)
at android.view.View.performClick(View.java:7659)
at android.view.View.performClickInternal(View.java:7636)
at android.view.View.-$$Nest$mperformClickInternal(Unknown Source:0)
at android.view.View$PerformClick.run(View.java:30156)
at android.os.Handler.handleCallback(Handler.java:958)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loopOnce(Looper.java:205)
at android.os.Looper.loop(Looper.java:294)
at android.app.ActivityThread.main(ActivityThread.java:8177)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:552)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:971)
Suppressed: kotlinx.coroutines.internal.DiagnosticCoroutineContextException: [StandaloneCoroutine{Cancelling}@b53a2bb, Dispatchers.Main.immediate]
3

There are 3 best solutions below

1
Dev4Life On

You can check if the fragment is attached to the activity or not using isAdded method.

Simply check it like this and do your stuff:

if(isAdded){
    // Fragment is attached.
}
0
Madhav Bhavsar On

Make sure that id in Menu should match id in Navigation.

also try adding or removing (+) in id in menu.

Menu XML:

<menu xmlns:android="http://schemas.android.com/apk/res/android">

<item android:id="@id/home"
// some code
/>

<item android:id="@id/favorite"
//some code
/>

</menu>

Navigation XML :

<navigation
//some code
android:id="@+id/main_navigation"
app:startDestination="@id/home">

<fragment
    android:id="@+id/home"
        // some code
/>
</fragment>
<fragment
    android:id="@+id/favorite"
        // some code
/>
    
</navigation>
7
Md Eusuf Uddin On

Get Activity within fragment and check Activity is null or not

 Activity activity = getActivity();
if (!isAdded() && activity == null) {
        return;
    }