CodexBloom - Programming Q&A Platform

Unexpected NullPointerException when using ViewModel with Hilt and StateFlow in Android 14

👀 Views: 77 đŸ’Ŧ Answers: 1 📅 Created: 2025-08-25
android hilt stateflow viewmodel jetpack Kotlin

I'm deploying to production and I'm working on a personal project and I'm experiencing a `NullPointerException` in my ViewModel when trying to access a StateFlow variable that is injected using Hilt. The behavior occurs intermittently, typically when the Fragment is being recreated after a configuration change. I have the following setup: ```kotlin @HiltViewModel class MyViewModel @Inject constructor(private val repository: MyRepository) : ViewModel() { private val _dataState = MutableStateFlow<Data?>(null) val dataState: StateFlow<Data?> = _dataState.asStateFlow() init { fetchData() } private fun fetchData() { viewModelScope.launch { _dataState.value = repository.getData() } } } ``` In my Fragment, I'm observing the StateFlow like this: ```kotlin @AndroidEntryPoint class MyFragment : Fragment() { private val viewModel: MyViewModel by viewModels() override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) lifecycleScope.launchWhenStarted { viewModel.dataState.collect { data -> // This line throws NullPointerException data?.let { showData(it) } } } } } ``` The stack trace shows the exception is thrown when the Fragment tries to collect from the StateFlow, indicating that `data` can be null at that point. I've ensured that `repository.getData()` returns a non-null value, and I'm initializing `_dataState` to null, which is expected since the data hasn't been fetched yet. I've tried wrapping the `collect` call in a `try-catch`, but that doesn't fix the underlying scenario. I suspect it may be related to the lifecycle of the ViewModel or the Fragment, but I'm not sure how to debug this further. Can anyone guide to figure out why I might be getting a `NullPointerException` here and how to safely handle the StateFlow updates in this situation? I'm working on a CLI tool that needs to handle this. How would you solve this? What would be the recommended way to handle this? This is for a application running on Windows 11. Thanks in advance!