Unexpected NullPointerException when using Room with LiveData in Fragment with LifecycleOwner on Android 14
I'm collaborating on a project where I'm not sure how to approach I'm sure I'm missing something obvious here, but I'm working with a `NullPointerException` when trying to observe a `LiveData` object from a Room database in my Fragment... The behavior occurs only when the Fragment is recreated after a configuration change, such as a screen rotation. Here is a snippet of my code: ```kotlin class MyFragment : Fragment() { private lateinit var myViewModel: MyViewModel override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { val view = inflater.inflate(R.layout.fragment_my, container, false) myViewModel = ViewModelProvider(this).get(MyViewModel::class.java) return view } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { myViewModel.getData().observe(viewLifecycleOwner, Observer { data -> // This line throws NullPointerException textView.text = data.text }) } } ``` My ViewModel code is as follows: ```kotlin class MyViewModel(application: Application) : AndroidViewModel(application) { private val repository: MyRepository = MyRepository(application) private val _data: LiveData<MyData> = repository.getData() // This fetches data from Room fun getData(): LiveData<MyData> { return _data } } ``` In my `getData` method inside the `Repository`, I am using a `LiveData` object from Room: ```kotlin class MyRepository(application: Application) { private val myDao: MyDao = MyDatabase.getDatabase(application).myDao() fun getData(): LiveData<MyData> { return myDao.getData() // returns LiveData<MyData> } } ``` The `NullPointerException` occurs specifically at `textView.text = data.text` which indicates that `data` is null when the observer is triggered after the Fragment is recreated. I have checked that the database and DAO are set up correctly, and they are returning data as expected before the rotation. I've also ensured the Fragment is properly attached to the `viewLifecycleOwner`. I tried to debug by logging the `data` inside the observer and confirmed it is indeed null at that point after the rotation. What could be causing this scenario? Any insights or tips on how to resolve this would be greatly appreciated! I'd really appreciate any guidance on this. I recently upgraded to Kotlin LTS. How would you solve this? Any feedback is welcome!