java.lang.IllegalStateException:API 响应后片段未附加到上下文

在我的应用程序中,我有一个用于显示数据的片段,以及一个用于更改应用程序中某些设置的设置活动。当我通过导航抽屉转到设置活动,然后返回主屏幕(不更改设置)时,应用程序崩溃并出现以下异常:

java.lang.IllegalStateException: Fragment NowWeatherFragment{b7914f8 (0e67ee0d-8776-45b5-9fd7-ee69841c31d1)} not attached to a context

它似乎是在 API 调用响应之后发生的,并且有一个关于 SO 的另一个答案的合理解释,但我尝试过的任何事情都无法解决这个问题。

我已经看到了其他几个与此相关的问题,但我无法将这些问题的答案应用到我的情况中。我尝试检查 isAttached() 但这并没有帮助,也对片段进行了空检查,但它仍然遇到相同的异常

与其发布所有课程,有些课程很长,这里是 github 存储库。它应该是相当轻量级的,并且很容易通过 Android Studio 在设备上运行 https://github.com/jollygreenegiant/SimpleWeather

我希望该应用程序会返回主屏幕并像启动时那样显示天气数据。

java.lang.IllegalStateException: Fragment NowWeatherFragment{b7914f8 (0e67ee0d-8776-45b5-9fd7-ee69841c31d1)} not attached to a context.

        at androidx.fragment.app.Fragment.requireContext(Fragment.java:765)

        at androidx.fragment.app.Fragment.getResources(Fragment.java:829)

        at com.jggdevelopment.simpleweather.fragments.NowWeatherFragment.setupViews(NowWeatherFragment.java:82)

        at com.jggdevelopment.simpleweather.fragments.NowWeatherFragment$3.onSharedPreferenceChanged(NowWeatherFragment.java:152)

        at android.app.SharedPreferencesImpl$EditorImpl.notifyListeners(SharedPreferencesImpl.java:612)

        at android.app.SharedPreferencesImpl$EditorImpl.commit(SharedPreferencesImpl.java:598)

        at com.jggdevelopment.simpleweather.fragments.MasterFragment.updateConditions(MasterFragment.java:263)

        at com.jggdevelopment.simpleweather.services.WeatherAPIUtils$2.onResponse(WeatherAPIUtils.java:92)

        at retrofit2.DefaultCallAdapterFactory$ExecutorCallbackCall$1$1.run(DefaultCallAdapterFactory.java:83)



慕尼黑8549860
浏览 187回答 2
2回答

MYYA

您需要调用unregisterOnSharedPreferenceChangeListener()您的onDestroyView()(的镜像onCreateView(),这是您注册侦听器的地方)。就像现在一样,您正在泄漏您的 Fragment,因为它SharedPreferences持有对您的侦听器的强烈引用,onSharedPreferenceChanged在您的 Fragment 的视图被销毁后继续将回调发送到它的井,导致您收到错误消息。

有只小跳蛙

Fragment生命周期过于繁杂Activity myactivity = getActivity(); if (isAdded() && myactivity != null) {...}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java