Fragment MyFragment not attached to Activity
I've found the very simple answer: isAdded()
:
Return
true
if the fragment is currently added to its activity.
@Override
protected void onPostExecute(Void result){
if(isAdded()){
getResources().getString(R.string.app_name);
}
}
To avoid onPostExecute
from being called when the Fragment
is not attached to the Activity
is to cancel the AsyncTask
when pausing or stopping the Fragment
. Then isAdded()
would not be necessary anymore. However, it is advisable to keep this check in place.
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();
}
}
}
Android - Fragment not attached to activity
You have problem with the line
pd.dismiss();
in onPostExecute
of your GetUrlData
. Put it inside if (isAdded ())
As per the answer of the question you reffered in your question. Your dialog uses the context of the activity.
EDIT
Add an if block in onPageSelected
method that checks if Fragment if attached i.e.
@Override
public void onPageSelected(int position) {
if(!isAdded ())
return;
for (int i = 0; i < dotsCount; i++) {
dots[i].setImageDrawable(getResources().getDrawable(R.drawable.nonselecteditem_dot));
}
if (position >= dotsCount) {
dots[0].setImageDrawable(getResources().getDrawable(R.drawable.selecteditem_dot));
} else {
dots[position].setImageDrawable(getResources().getDrawable(R.drawable.selecteditem_dot));
}
}
Fragment not attached to Activity while loading adapter
You are calling observe()
with requireActivity()
- your Activity's Lifecycle. That means you will continue to receive results until your Activity is stopped - i.e., it isn't tied to your Fragment's lifecycle at all, meaning it will continue to receive results even after your fragment is detached. You should never use requireActivity()
with observe()
in a Fragment.
Fragments have a special lifecycle specifically tied to when their views are created - getViewLifecycleOwner()
. This is what you should be using for your observe
:
shopViewModel.getDeptos().observe(getViewLifecycleOwner(), new Observer<Resource<List<Departamento>>>() {
Related Topics
How to Automatically Update Application on Android
How to Set Custom Header in Volley Request
Android 4.3 Menu Item Showasaction="Always" Ignored
Replace Selector Images Programmatically
How to Listen for Changes in Contact Database
In Eclipse, Unable to Reference an Android Library Project in Another Android Project
Change the Circle Color of Radio Button
How to Know an Application Is Installed from Google Play or Side-Load
Programmatically Select Item Listview in Android
Converting JSONarray to Arraylist
How to Add a Textview to a Linearlayout Dynamically in Android
How to Pass Arraylist of Objects from One to Another Activity Using Intent in Android
Android Asynctask Example and Explanation
Recyclerview Horizontal Scroll Snap in Center
Find Distance Between Two Points on Map Using Google Map API V2
Media Player Called in State 0, Error (-38,0)
Error:(6, 0) Gradle Dsl Method Not Found: 'Google()'
The Number of Method References in a .Dex File Cannot Exceed 64K API 17