简体   繁体   English

如果项目存在于数据库中,为什么 Room 查询会返回 null?

[英]Why is Room query returning null if the item exists in the database?

I have inserted a Movie into my database and want to query the database based on the movieId.我已将电影插入到我的数据库中,并希望根据 movieId 查询数据库。 I can confirm that the movieId is in my database using the Stetho inspector.我可以使用 Stetho 检查器确认 movieId 在我的数据库中。 Why am I getting null?为什么我得到 null?

DAO

@Dao
public interface MoviesDao {

    @Insert(onConflict = OnConflictStrategy.IGNORE)
    void insertMovie(Movie movie);

    @Transaction
    @Query("SELECT * FROM movie WHERE id = :movieId ")
    LiveData<Movie> getMovie(long movieId);

ViewModel视图模型

    public void getMovieFromDatabase(Movie movie) {
        LiveData<Movie> result = movieRepository.getMovieFromDatabase(movie);
        Log.d(TAG, "result is: " + result.getValue());
    }

Repository存储库

    public LiveData<Movie> getMovieFromDatabase(Movie movie) {
        Log.d(TAG, "Movie id: " + movie.getId());
        return dbInstance.moviesDao().getMovie(movie.getId());
    }

Result from Logcat来自 Logcat 的结果

Movie id: 419704
result is: null

Image of database.数据库图像。 Clearly movie id 419704 exists (second item):显然电影 id 419704 存在(第二项): 在此处输入图像描述

getMovie() is your DAO method. getMovie()是您的 DAO 方法。 It returns a LiveData .它返回一个LiveData That will cause Room to do the database I/O on a background thread.这将导致 Room 在后台线程上执行数据库 I/O。

However, you immediately attempt to get the value out of the LiveData .但是,您立即尝试从LiveData中获取值。 That will not work most of the time, as the background thread will not have completed its work yet.这在大多数情况下是行不通的,因为后台线程还没有完成它的工作。

Either:任何一个:

  • Get rid of the LiveData and have getMovie() return the results directly, and call getMovie() on a background thread, or摆脱LiveData并让getMovie()直接返回结果,并在后台线程上调用getMovie() ,或者

  • observe() the LiveData , rather than attempt to use its value immediately observe() LiveData ,而不是立即尝试使用它的值

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

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