我如何从 Room 数据库中获取一个项目?

How can i get one item from Room database?

所以,我的应用程序中有两个 ViewModel 和两个屏幕。第一个屏幕用于显示日记项目元素列表,第二个屏幕用于显示日记项目的详细信息。在第二个 ViewModel 中,我有一个 id 可以从数据库中获取记录,但可以找到它。我该怎么做才能得到它?

道:

interface DiaryDao {

    @Query("SELECT * FROM diaryItems")
    fun getAllDiaryPosts(): LiveData<List<DiaryItem>>

    @Query("Select * from diaryItems where id = :id")
    fun getDiaryPostById(id: Int) : DiaryItem

    @Query("Delete from diaryItems where id = :index")
    fun deleteDiaryPostByIndex(index : Int)

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun insertDiaryPost(diaryItem: DiaryItem)

    @Update
    suspend fun updateDiaryPost(diaryItem: DiaryItem)

    @Delete
    suspend fun deleteDiaryPost(diaryItem: DiaryItem)

    @Query("Delete from diaryItems")
    suspend fun deleteAllDiaryItems()
    
}

存储库

class DiaryRepository @Inject constructor(private val diaryDao: DiaryDao) {

    val readAllData: LiveData<List<DiaryItem>> = diaryDao.getAllDiaryPosts()
   
    suspend fun getDiaryPostDyIndex(index: Int): DiaryItem {
        return diaryDao.getDiaryPostById(index)
    }
}

第一个视图模型

@HiltViewModel
class PostListViewModel
@Inject
constructor(
    private val diaryRepository: DiaryRepository,
) : ViewModel() {
    private var allDiaryItems: LiveData<List<DiaryItem>> = diaryRepository.readAllData
}

第二个视图模型

@HiltViewModel
class PostDetailViewModel
@Inject
constructor(
    private val savedStateHandle: SavedStateHandle,
    private val diaryRepository: DiaryRepository
) : ViewModel() {


    sealed class UIState {
        object Loading: UIState()
        data class Success(val currentPosts: DiaryItem) : UIState()
        object Error : UIState()
    }

    val postDetailState: State<UIState>
        get() = _postDetailState
    private val _postDetailState = mutableStateOf<UIState>(UIState.Loading)


    init {
        viewModelScope.launch (Dispatchers.IO) {
           try {

                   val diaryList: DiaryItem = diaryRepository.getDiaryPostDyIndex(2) //it is for test
                   _postDetailState.value = UIState.Success(diaryList)

           } catch (e: Exception) {
               withContext(Dispatchers.Main) {
                   _postDetailState.value = UIState.Error
               }
           }
        }

    }

}

我确定您遇到了错误。因为您更新了 IO 线程中的 UI 状态

fun getDairyItem(itemId: Int){
viewModelScope.launch (Dispatchers.IO) {
     try {
           val diaryList: DiaryItem = diaryRepository.getDiaryPostDyIndex(itemId)
           withContext(Dispatchers.Main) {
              _postDetailState.value = UIState.Success(diaryList)
           } 
           } catch (e: Exception) {
               withContext(Dispatchers.Main) {
                   _postDetailState.value = UIState.Error
               }
           }
        }
}