我的android异常系列——Fragment XXX not attached to Activity
来源:互联网 发布:linux设置静态ip 编辑:程序博客网 时间:2024/05/20 11:22
我的异常系列目录为:http://www.jianshu.com/p/cb10697226ef
- 直接切入主题。出现这个问题后,我们定位到代码中的位置一般是getString或者getResources导致的!
- 既然是Fragment出现的问题。我们直接定位到Fragment的源代码,检索错误的字符串,马上我们可以看到Fragment的getResources()方法(getString最终也会调用这个方法),如下
/** * Return <code>getActivity().getResources()</code>. */ final public Resources getResources() { if (mHost == null) { throw new IllegalStateException("Fragment " + this + " not attached to Activity"); } return mHost.getContext().getResources(); }
- 从上面的代码中我们可以明白,抛出异常的原因是mHost == null,而这个mHost会在Fragment被回收后置为null(详细的细节可以查看FragmentManager这个类),出现这种状况是由于我们退出当前Fragment后某个线程还调用getString等方法
- 所以如果Fragment被回收后我们再调用这个方法,就会抛出这个异常
解决方案:
1.错误已经和明显的指出not attached to Activity了,所以我们在调用getString等方法前需要判断一下Fragment是否已经add到Activity中(通过Fragment的isAdded方法)
2.直接在Fragment创建的时候通过getActivity获取Activity上下文对象赋值给成员变量,后面直接用即可
阅读全文
0 0
- 我的android异常系列——Fragment XXX not attached to Activity
- Fragment xxx not attached to Activity
- android开发Fragment not attached to Activity异常解决
- Android问题解决之Fragment not attached to Activity异常
- Fragment not attached to Activity 异常
- 关于Fragment not attached to Activity 异常
- Fragment not attached to Activity 异常
- Fragment not attached to Activity 异常
- Fragment not attached to Activity 异常
- Fragment not attached to activity 异常
- Fragment not attached to Activity 异常
- Fragment not attached to Activity 异常
- Android - Fragment StepCounterStaticFragment not attached to Activity
- Android IllegalStateException: Fragment not attached to Activity
- Android IllegalStateException: Fragment not attached to Activity
- Android Fragment异常:java.lang.IllegalStateException: Fragment XXXFragment not attached to Activity
- Android Fragment异常java.lang.IllegalStateException: Fragment not attached to Activity
- Fragment not attached to Activity
- 微信小程序开发之真机测试 地图定位 map API 无法获取当前位置的问题
- angualr操作dom
- 在二叉树中找到累加和为指定值的最长路径长度
- 数据仓库技术的简单阐述
- TabLayout设置下划线(Indicator)长度
- 我的android异常系列——Fragment XXX not attached to Activity
- jquery 国际化使用
- 纯java项目使用hibernateSessionFactory访问数据库
- ftp文件上传下载
- LeetCode
- 运动框架和隐藏边框
- 在一个maven项目中从头到尾grpc的使用
- 关于BETA、RC、ALPHA、Release、GA等版本号的意义
- Spring之AOP入门(二)