Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.7k views
in Technique[技术] by (71.8m points)

android - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...