Java.Lang.Illegalstateexception: Fragment Not Attached to Activity

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() 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();
}
}
}

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));
}
}

java.lang.IllegalStateException: Fragment not attached to a context

The problem seems to be, that your fragment is listening to some events (via UserController and QueryResult) and these are fired before the fragment is attached to context.

Try to unregister the fragment when it becomes detached and to them again after attaching (LiveData can also help with this). Another way could be to receive and store the event while detached and only process it after attaching.

Fragment not attached to a context

Create a fragment instance is not enough.
It needs to be attached to Activity through a transaction:

getFragmentManager()
.beginTransaction()
.replace(R.id.container_layout, fragment)
.commit();

After a successful commit, onAttach method in the fragment is called, the view is created and then you can interact with its views.

In your case, create the fragment instance and attach it in activity onCreate, then call sortByPopularity later in a click event.

Read more about fragment life cycle: https://developer.android.com/guide/components/fragments

IllegalStateException: Fragment xx not attached to Activity

There's two issues:

  1. You're unconditionally calling loadFragment(new MonthlyFragment()); in your Monthly_paid's onCreate(). Fragments automatically restore their state, so this should only be done if (savedInstanceState == null) to avoid overriding the Fragments being restored.

  2. You never call mBillingClient.endConnection(), so any asynchronous callbacks (like your onBillingSetupFinished()) aren't cancelled when your Fragment gets destroyed. Since you call startConnection() in onCreateView(), the logical place to put endConnection() is in onDestroyView().

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



Leave a reply



Submit