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));
}
}
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:
You're unconditionally calling
loadFragment(new MonthlyFragment());
in yourMonthly_paid
'sonCreate()
. Fragments automatically restore their state, so this should only be doneif (savedInstanceState == null)
to avoid overriding the Fragments being restored.You never call
mBillingClient.endConnection()
, so any asynchronous callbacks (like youronBillingSetupFinished()
) aren't cancelled when your Fragment gets destroyed. Since you callstartConnection()
inonCreateView()
, the logical place to putendConnection()
is inonDestroyView()
.
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
Getting Started with Open Nfc Emulator
How to Play Local Swf Files in a Webview
Enabling General JavaScript in Webviewclient
Get Context Inside Onclick(Dialoginterface V, Int Buttonid)
In What Period Does the Firebase's App Token Changes and How to Manage It
Cannot Resolve Method 'Getsupportfragmentmanager ( )' Inside Fragment
How to Set Notification with Custom Sound in Android
Job Scheduler Not Running on Android N
How to Extract the Text from the Selected Item on the Listview
Android - Listview - Performitemclick
Running Task Periodicaly(Once a Day/Once a Week)
Bitmap Is Returning Null from Bitmapfactory.Decodefile(Filename)
Show Error on the Tip of the Edit Text Android
Disable or Prevent Multitouch in Activity
Start a Service in a Separate Process Android