解决java.lang.IllegalStateException: Fragment not attached to Activity
2016-05-23 16:58
633 查看
转载至:http://stackoverflow.com/questions/28672883/java-lang-illegalstateexception-fragment-not-attached-to-activity
This error happens due to the combined effect of two factors:
The HTTP request, when complete, invokes either onResponse() or onError() (which work on the main thread) without knowing whether the Activity is still in the foreground or not. If the Activity is gone (the user navigated elsewhere), getActivity() returns null.
The Volley Response is expressed as an anonymous inner class, which implicitly holds a strong reference to the outer Activity class. This results in a classic memory leak.
To solve this problem, you should always do:
and also, use isAdded() in the onError() method as well:
This error happens due to the combined effect of two factors:
The HTTP request, when complete, invokes either onResponse() or onError() (which work on the main thread) without knowing whether the Activity is still in the foreground or not. If the Activity is gone (the user navigated elsewhere), getActivity() returns null.
The Volley Response is expressed as an anonymous inner class, which implicitly holds a strong reference to the outer Activity class. This results in a classic memory leak.
To solve this problem, you should always do:
Activity activity = getActivity(); if(activity != null){ // etc ... }
and also, use isAdded() in the onError() method as well:
@Override public void onError(VolleyError error) { Activity activity = getActivity(); if(activity != null && isAdded()) mProgressDialog.setVisibility(View.GONE); if (error instanceof NoConnectionError) { String errormsg = getResources().getString(R.string.no_internet_error_msg); Toast.makeText(activity, errormsg, Toast.LENGTH_LONG).show(); } } }
相关文章推荐
- java的Arrays工具类实战
- Java面向对象编程 第一章 面向对象开发方法概述
- Java面向对象 第一章 面向对象开发方法概述
- Spring 框架的设计理念与设计模式分析
- java.lang.OutOfMemoryError处理错误
- java 数据采集
- Maven设置项目java默认编译版本
- java 字符串缓冲池 String缓冲池
- Java 协变数组和类型擦除(covariant array & type erasure)
- JAVA基础教程6:运行时类型识别(RTTI)
- Thinking in java 之 内部类
- Java Arrys的用法
- 《Head first in Java学习总结与收获》
- Spring 中配置log4j日志功能
- java之Timer
- Java UDP
- Java实现lucene搜索功能
- 阿里云服务器Ubuntu安装jdk7
- java I/O流的理解
- Spring MVC 配置详解