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
2.2k views
in Technique[技术] by (71.8m points)

android - Fragment has not been attached yet

After reading posts on this exception, I can't understand what I need to do to correct this error. Besides, I can't even reproduce it... This happens sometimes on some devices but I don't understand how...

my logs :

Fatal Exception: java.lang.IllegalStateException
Fragment a has not been attached yet my.app.HostFragment.addFragment

HostFragment class :

fun addFragment(fragment: Fragment) {
        childFragmentManager.beginTransaction()
          .add(R.id.fragment_root_container, fragment)
          .addToBackStack(null)
          .commit()
}

MainActivity class :

fun openNewChampionFragment() {
        val hostFragment = pagerAdapter.getItem(viewpager.currentItem) as HostFragment
        hostFragment.addFragment(ChampionFragment.newInstance())
}

ViewPager Adapter :

class ViewPagerAdapter(manager: FragmentManager) : FragmentStatePagerAdapter(manager, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT) {

    private var fragments: MutableList<Fragment> = mutableListOf()

    fun addFragments(fragments: List<Fragment>) {
        this.fragments = fragments.toMutableList()
    }

    override fun getItem(position: Int): Fragment {
        return fragments[position]
    }

    override fun getCount(): Int {
        return fragments.size
    }

    fun clearStack(index: Int){
        (fragments[index] as HostFragment).clearAllStack()
    }
}

I always call addFragment from my MainActivity with a new fragment instance (I don't reuse the instance of the old fragments.)

Which fragment has not been attached ? My HostFragment or the new one that i'm trying to add.

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

Your app crashes because the implementation of FragmentStatePagerAdapter is incorrect.

// private var fragments: MutableList<Fragment> = mutableListOf() // <-- remove this line entirely

You mustn't keep a list of fragments in your Fragment*PagerAdapter, because the system recreates the Fragments, and the one you'll be invoking in that list will never actually be added to the FragmentManager.

Something you can do is switch FragmentStatePagerAdapter to FragmentPagerAdapter, then you can apply App crash after activity has been killed in background and How to get elements of fragments created by ViewPager in MainActivity? .

To reproduce your crash, refer to Singleton object becomes null after app is resumed .


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

2.1m questions

2.1m answers

60 comments

57.0k users

...