简体   繁体   中英

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. I can confirm that the movieId is in my database using the Stetho inspector. Why am I getting 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

Movie id: 419704
result is: null

Image of database. Clearly movie id 419704 exists (second item): 在此处输入图像描述

getMovie() is your DAO method. It returns a LiveData . That will cause Room to do the database I/O on a background thread.

However, you immediately attempt to get the value out of the 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

  • observe() the LiveData , rather than attempt to use its value immediately

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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