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()
oronError()
(which work on the main thread) without knowing whether theActivity
is still in the foreground or not. If theActivity
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 outerActivity
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();
}
}
}
Fragment lifecycle is very complex and full of bugs, try to add:
Activity activity = getActivity();
if (isAdded() && activity != null) {
...
}
I Found Very Simple Solution isAdded() method which is one of the fragment method to identify that this current fragment is attached to its Activity or not.
we can use this like everywhere in fragment class like:
if(isAdded())
{
// using this method, we can do whatever we want which will prevent **java.lang.IllegalStateException: Fragment not attached to Activity** exception.
}