Tag Archives: Change a bug to a day

[Solved] Fragment not attached to an activity

Error Description:

Make a network request in the fragment, jump to other pages before the request ends, and then jump back from other pages. The compiler reports the following error:

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.mio.hygrothermograph, PID: 32449
    java.lang.IllegalStateException: Fragment HomeFragment{86a99ac} (d6728a71-7df5-4f7b-ae10-e3e449d3b451) not attached to an activity.
        at androidx.fragment.app.Fragment.requireActivity(Fragment.java:928)
        at com.mio.hygrothermograph.ui.HomeFragment$getHomeInfoByRxJava$1.onNext(HomeFragment.kt:91)
        at com.mio.hygrothermograph.ui.HomeFragment$getHomeInfoByRxJava$1.onNext(HomeFragment.kt:70)
        at io.reactivex.internal.operators.observable.ObservableObserveOn$ObserveOnObserver.drainNormal(ObservableObserveOn.java:201)
        at io.reactivex.internal.operators.observable.ObservableObserveOn$ObserveOnObserver.run(ObservableObserveOn.java:255)
        at io.reactivex.android.schedulers.HandlerScheduler$ScheduledRunnable.run(HandlerScheduler.java:119)
        at android.os.Handler.handleCallback(Handler.java:900)
        at android.os.Handler.dispatchMessage(Handler.java:103)
        at android.os.Looper.loop(Looper.java:219)
        at android.app.ActivityThread.main(ActivityThread.java:8668)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:513)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1109)

reason

Execute a time-consuming task in the Fragment, and rebuild the Activity before the task is completed. Getactivity() will be null, and null pointer exceptions will be caused in all places where parameters need to be obtained through the activity. For example, the getResource() method.

Solution:

The isAdded() judgment is performed where the parameters need to be obtained through the Activity to judge whether the current Fragment is added to the activity. Only when the Fragment is added to the activity can getResource be obtained.