简体   繁体   English

Kotlin DAO 访问时返回 null

[英]Kotlin DAO return null when try to access

I am new to Android development.我是 Android 开发的新手。 When I try to access the id from the Room.当我尝试从房间访问 id 时。 I get null. Is there something I did wrong?我得到 null。我做错了什么吗?

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())

When you call getEnglishId.value , the database read hasn't completed and the LiveData contains the initial value null .当您调用getEnglishId.value时,数据库读取尚未完成,LiveData 包含初始值null You need to observe the LiveData in your fragment.您需要观察片段中的 LiveData。

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)
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM