Home > Software engineering >  Kotlin DAO return null when try to access
Kotlin DAO return null when try to access

Time:10-10

I am new to Android development. When I try to access the id from the Room. I get null. Is there something I did wrong?

Language

@Entity(tableName = "language_table6")
data class Language(
    val isChecked: Boolean = false,
    val language: String,
    val isFavourite: Int = 0,
    @PrimaryKey(autoGenerate = true) val id: Int = 0

)

LanguageDao

@Query("SELECT id FROM language_table6 WHERE language = :language")
     fun getEnglishId(language: String): LiveData<Long>

FavouriteViewModel

class FavouriteViewModel @Inject constructor(
    val languageDao: LanguageDao
) : ViewModel() {
val favouriteLanguage = languageDao.getFavouriteLanguageByName().asLiveData()
// Try to access get the id in language model
val englishObject: LiveData<Long> = languageDao.getEnglishId("English")

fun onFavouriteLanguage(languageId: Int) = CoroutineScope(Dispatchers.IO).launch {
    languageDao.resetFavouriteLanguage()
    languageDao.setFavouriteLanguage(languageId)
}

}

FavouriteFragment

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        val binding = FavouriteBottomSheetBinding.bind(view)
        val favouriteAdapter = FavouriteAdapter(this)
        
        // Try to try to get the value from viewModel  
        val getEnglishId: LiveData<Long> = viewModel.englishObject

        d("readEnglishId", getEnglishId.value.toString())

CodePudding user response:

When you call getEnglishId.value, the database read hasn't completed and the LiveData contains the initial value null. You need to observe the LiveData in your fragment.

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    val binding = FavouriteBottomSheetBinding.bind(view)
    val favouriteAdapter = FavouriteAdapter(this)
        
    viewModel.englishObject.observe(viewLifecycleOwner) { id ->
        // Here you can use the live data value (id)
    }
}
  • Related