CodexBloom - Programming Q&A Platform

Unexpected Null Pointer handling with Room Database on Android 14 when using Flow

๐Ÿ‘€ Views: 371 ๐Ÿ’ฌ Answers: 1 ๐Ÿ“… Created: 2025-06-12
android room kotlin flow Kotlin

I've encountered a strange issue with I'm refactoring my project and After trying multiple solutions online, I still can't figure this out... After trying multiple solutions online, I still can't figure this out... Iโ€™m working with a `NullPointerException` in my Android 14 app that uses Room with Kotlin Flow for data observation. The scenario occurs when I try to collect data from a Flow in my ViewModel. I have set up my DAO and database entities correctly, but it seems that the Flow is not emitting any values, leading to a null state. Hereโ€™s a simplified version of my DAO: ```kotlin @Dao interface UserDao { @Query("SELECT * FROM users") fun getAllUsers(): Flow<List<User>> } ``` In my ViewModel, I am trying to collect the Flow like this: ```kotlin class UserViewModel(private val userDao: UserDao) : ViewModel() { val users: StateFlow<List<User>> = userDao.getAllUsers().stateIn(viewModelScope, SharingStarted.Lazily, emptyList()) } ``` I also have a fragment that observes this StateFlow: ```kotlin class UserFragment : Fragment() { private val viewModel: UserViewModel by viewModels() override fun onViewCreated(view: View, savedInstanceState: Bundle?) { lifecycleScope.launchWhenStarted { viewModel.users.collect { userList -> // This line throws NullPointerException userList.forEach { user -> Log.d("User", user.name) } } } } } ``` When I run the app, I see the behavior `Kotlin NullPointerException: Attempt to invoke virtual method 'java.lang.String com.example.app.User.getName()' on a null object reference` in the logs. I have ensured that my database is set up correctly and that the User entity has a non-nullable name property. I have checked if the database has been populated correctly, and it seems fine since I can see the users in the Room inspector. However, it appears that the Flow is not emitting a non-null list of users. Iโ€™ve tried switching the `stateIn` method to `shareIn` with different strategies, but it still doesnโ€™t solve the scenario. Any insights on what might be going wrong or how I can debug this further would be appreciated! How would you solve this? This is part of a larger service I'm building. Is there a better approach? Cheers for any assistance! Any advice would be much appreciated.