当前位置:   article > 正文

解决java.lang.IllegalStateException: Fragment not attached to Activity

java.lang.illegalstateexception: fragment not attached to a context.

转载至: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:

Activity activity = getActivity();
if(activity != null){

    // etc ...

}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

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();
        }
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家小花儿/article/detail/253163
推荐阅读
相关标签
  

闽ICP备14008679号