为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

慕尼黑8549860 2023-03-17 10:19:11
在我的应用程序中,我有一个用于显示数据的片段,以及一个用于更改应用程序中某些设置的设置活动。当我通过导航抽屉转到设置活动,然后返回主屏幕(不更改设置)时,应用程序崩溃并出现以下异常: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)
查看完整描述

2 回答

?
MYYA

TA贡献1868条经验 获得超4个赞

您需要调用unregisterOnSharedPreferenceChangeListener()您的onDestroyView()(的镜像onCreateView(),这是您注册侦听器的地方)。

就像现在一样,您正在泄漏您的 Fragment,因为它SharedPreferences持有对您的侦听器的强烈引用,onSharedPreferenceChanged在您的 Fragment 的视图被销毁后继续将回调发送到它的井,导致您收到错误消息。


查看完整回答
反对 回复 2023-03-17
?
有只小跳蛙

TA贡献1824条经验 获得超8个赞

Fragment生命周期过于繁杂


Activity myactivity = getActivity(); 

if (isAdded() && myactivity != null) {

...

}


查看完整回答
反对 回复 2023-03-17
  • 2 回答
  • 0 关注
  • 139 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号