I have a bottomNavView with Viewpager2 using FragmentStateAdapter. I have 4 tabs. Before i was using viewpager. then, i switch to viewpager2 because of this error. But on viewpager2 same error is occurring.
When i switch between apps tiktok,facebook,instagram and come back to my app. its recreated. all 4 fragment are called from oncreateview() and so on. but my back button was not working. because onBackPress. I am accessing fragment. But the fragments are null. Althought, they are being recreated and displayed.
if (binding.viewPager.currentItem == 3) {
val frag = sectionsPagerAdapter.fragment3
}
after spending an entire day I was able to fix the problem by assigning it back to fragments but this doesn't seem like the best solution.
override fun onResume() {
super.onResume()
val activity = activity as ActivityMain
activity.sectionsPagerAdapter.fragment2 = this
}
In Manifest
<activity
android:name=".activities.ActivityMain"
android:configChanges="keyboardHidden|orientation|screenSize"
android:exported="true"
android:label="@string/title_activity_navigation"
android:screenOrientation="portrait"
/>
This is my viewpager2 Adapter. before I was using lateinit val to fragments. still, i was getting error. At that time fragment was not null but it could not pass isadded. Another thing is that createFragment doesn't get called when activity is auto_recreated. but all fragment calls oncreateview
class SectionsPagerAdapter( activity: FragmentActivity) : FragmentStateAdapter( activity) {
val TAG = "SectionsPagerAdapter"
var fragment0: Fragment0? = null
var fragment3: Fragment1? = null
var fragment1: Fragment2? = null
var fragment2: Fragment3? = null
override fun getItemCount(): Int {
return 4
}
override fun createFragment(position: Int): Fragment {
if (position == 0) {
if(fragment0 == null){
fragment0 = Fragment0()
}
return fragment0!!
}
if (position == 1) {
if(fragment1 == null){
fragment1 = Fragment1()
}
return fragment1!!
}
if (position == 2) {
if(fragment2 == null){
fragment2 = Fragment2()
}
return fragment2!!
}
if (position == 3) {
if(fragment3 == null){
fragment3 = Fragment3()
}
return fragment3!!
}
return Fragment0()
}
}