CodexBloom - Programming Q&A Platform

Strange behavior with ViewPager2 and FragmentStateAdapter when using nested fragments on Android 14

πŸ‘€ Views: 38 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-10
android viewpager2 fragments kotlin

I'm stuck on something that should probably be simple. I've been struggling with this for a few days now and could really use some help... I've been struggling with this for a few days now and could really use some help. I'm experiencing an issue with `ViewPager2` and `FragmentStateAdapter` when trying to implement a nested fragment setup on Android 14. The outer `ViewPager2` works fine, but when I swipe to the next page, the nested fragments do not seem to retain their state correctly. I expect each fragment's state to be maintained, but instead, I see a `NullPointerException` being thrown when trying to access fragment views. Here’s a simplified version of what I have set up: ```kotlin class MyFragment : Fragment() { private lateinit var viewPager: ViewPager2 override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { return inflater.inflate(R.layout.fragment_my, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) viewPager = view.findViewById(R.id.viewPager) viewPager.adapter = MyPagerAdapter(this) } } class MyPagerAdapter(fragment: Fragment) : FragmentStateAdapter(fragment) { override fun getItemCount(): Int = 5 override fun createFragment(position: Int): Fragment { return NestedFragment.newInstance(position) } } class NestedFragment : Fragment() { private var position: Int = 0 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) arguments?.let { position = it.getInt(ARG_POSITION) } } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { return inflater.inflate(R.layout.fragment_nested, container, false) } companion object { private const val ARG_POSITION = "position" fun newInstance(position: Int) = NestedFragment().apply { arguments = Bundle().apply { putInt(ARG_POSITION, position) } } } } ``` When I swipe between the pages, I get the following error: `java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View com.example.app.NestedFragment.getView()' on a null object reference`. I've tried calling `setRetainInstance(true)` on the `NestedFragment`, but it didn't resolve the issue. I also ensured that I'm not holding strong references to the fragment views outside their lifecycle. Any insights or suggestions on how to fix this would be greatly appreciated! What's the best practice here? For context: I'm using Kotlin on Ubuntu. My team is using Kotlin for this REST API. I'd really appreciate any guidance on this.