简体   繁体   中英

java.lang.IllegalStateException: Fragment not attached to Activity in Android

I am working on an application in which I have multiple Fragments inside my Activity but the problem is that sometimes on " BackPress " my application got crashed and it shows me error ie " java.lang.IllegalStateException: Fragment not attached to Activity in Android ". And my logcat redirect me to Toast ie

Code

catch (Exception e) {
    Toast.makeText(getActivity(), R.string.some_error_occured, Toast.LENGTH_LONG).show();
    e.printStackTrace();
}

Have I done something wrong with Toast ?

if you have a viewpager in your fragments then you need to add in your viewpager adapter.

 @Override
public Parcelable saveState() {
    return null;
}

hey check if you are attached to activity or not then make context related calls like getString which you are doing in Toast. so move your code inside

isAdded() : Return true if the fragment is currently added to its activity.

if (isAdded()){
    //your code goes here
} else {
    //handle the case
}

docs

Check back stack count and remove all active fragments then call parent class's onBackPressed() method.

override fun onBackPressed() {
    supportFragmentManager.beginTransaction().remove(fragment)
    super.onBackPressed()
}

It's crashing because when you are pressing back button that time your activity is not attached to the view and if you want to show toast message then you need an instance of that activity. Try this, to check fragment is attached to the activity

           Activity activity = getActivity();

           if(activity! = null && isAdded){
             Toast.makeText(getActivity, "Show message", Toast.LENGTH_SHORT).show();
           }

The answer is very simple. Your fragment is not getting proper context refrence you should do like this it will never force stop.

Take reference of your activity in which fragments are integrated. For example, your fragment is lying under MainActivity so you should code like this

 MainActivity mainactivity;

 @Override 
 public void onCreate(Bundle bundle) {
 super.onCreate(bundle);

     // use this mainactivity object instead of getActivity() or getContext() or requireContext() or requireActivity() 
     mainactivity = (MainActivity) getActivity();
}

I guarantee, your app will work smoothly without any single error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM