CodexBloom - Programming Q&A Platform

Unexpected NullPointerException when accessing LiveData from ViewModel after Configuration Change

👀 Views: 484 đŸ’Ŧ Answers: 1 📅 Created: 2025-07-14
android viewmodel livedata configuration-change kotlin

I'm integrating two systems and I've looked through the documentation and I'm still confused about I'm stuck on something that should probably be simple... I'm encountering a `NullPointerException` when trying to access a `LiveData` object from my `ViewModel` after a configuration change, specifically when the device is rotated. My `ViewModel` holds a `MutableLiveData<String>` that gets populated with data from a repository. Here's the relevant part of my `ViewModel`: ```kotlin class MyViewModel : ViewModel() { private val _data = MutableLiveData<String>() val data: LiveData<String> get() = _data fun fetchData() { // Simulating data fetch _data.value = "Hello, World!" } } ``` In my `Activity`, I observe this `LiveData` like this: ```kotlin class MyActivity : AppCompatActivity() { private lateinit var viewModel: MyViewModel override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) viewModel = ViewModelProvider(this).get(MyViewModel::class.java) viewModel.data.observe(this, { value -> // This line throws NullPointerException Log.d("Data", value) }) viewModel.fetchData() } } ``` I have confirmed that the `fetchData()` method is called, but when I rotate the device, I receive a `NullPointerException` in the log stating `Attempt to invoke virtual method 'java.lang.String java.lang.String.toString()' on a null object reference`. I suspect the issue might be related to the way I am observing the `LiveData` or the lifecycle of the `Activity`. I've also tried using `savedInstanceState` to store state, but it doesn't seem to help. Any insights on how to appropriately handle this situation and avoid the `NullPointerException`? My `minSdkVersion` is 21 and I am using AndroidX libraries. My development environment is macOS. What am I doing wrong? This is part of a larger API I'm building. What am I doing wrong? This is part of a larger CLI tool I'm building. Any ideas what could be causing this? I'd love to hear your thoughts on this.