Welcome to OGeek Q&A 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 Reply

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 .


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...