[Solved] java.lang.IllegalStateException: Fragment not attached to a context
If you use android ViewPager or SectionsPagerAdapter or simply fragment in activity, you attach fragment like this
Fragment fragment = (Fragment) new MyFragment();
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frame, fragment)
.commit();
But after rotation, you got error java.lang.IllegalStateException: Fragment not attached to a context
I’ve searched 1 hour, tried to use requireContext()
, which do nothing and found solution. But not on the internet, but in my old code from 2018 ;)
In activity that hosts fragment do this:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_activity);
//your code
//start of solution
if (savedInstanceState != null) {
return;
}
//end of solution
Fragment fragment = (Fragment) new MyFragment();
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frame, fragment)
.commit();
}
Thanks for coming and happy coding!