Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fragment has not been attached yet?

Below is my code. What i am trying to achieve is that i am displaying viewholder inside my Recycler view. Inside view pager i am displaying one fragment and on swipe left i am displaying another fragment. But when i run the app. App is crashing.Don't know where i am going wrong. I think it's some where in fragment's concept. Please do help me

 @Override  public void onBindViewHolder(ManageCustomerViewHolder holder, int position)   {      holder.viewPager.setAdapter(new MyPageAdapter(fragmentManager, fragments));  }   private List<Fragment> getFragments()   {      List<Fragment> fList = new ArrayList<Fragment>();      fList.add(MyFragment.newInstance("Fragment 1"));      fList.add(Myfragment1.newInstance("Fragment 2"));       return fList;  }   public class ManageCustomerViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener  {     ViewPager viewPager;     viewPager = (ViewPager) itemView.findViewById(R.id.viewpager);      itemView.setOnClickListener(this);  } 

This is what the error is :

java.lang.IllegalStateException: Fragment has not been attached yet.

like image 488
Srikanth G Avatar asked Apr 22 '17 17:04

Srikanth G


2 Answers

I was facing the same issue in my app.

Stack Trace:

java.lang.IllegalStateException: Fragment has not been attached yet. android.support.v4.app.Fragment.instantiateChildFragmentManager(Fragment.java:2154) android.support.v4.app.Fragment.getChildFragmentManager(Fragment.java:704) 

The app was crashing at this line:

function performSomeActionInChildFragments() {     List<Fragment> fragments = getChildFragmentManager().getFragments();     ... } 

This happens when the fragment is no longer attached to its parent activity/fragment. So a simple isAdded() check should resolve this issue for you.

Fix:

function performSomeActionInChildFragments() {     if (!isAdded()) return;     List<Fragment> fragments = getChildFragmentManager().getFragments();     ... } 

From documentation:

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

like image 53
Akshay Goyal Avatar answered Sep 27 '22 21:09

Akshay Goyal


Update the Support Library Revision to 27.0.2 to solve the problem. See changelog.

like image 33
C.BY Avatar answered Sep 27 '22 21:09

C.BY