Android房间持久性查询返回空值

时间:2018-07-06 00:11:49

标签: java android android-room

我目前正在学习如何利用Android Room Persistence库。以下代码在尝试查询(findById)与int(ID)关联的已保存布尔值时遇到问题。尝试这样做时,它反复出现null。这里有我忽略的问题吗?有人可以指出我在这里做错的正确方向吗?谢谢。

收藏电影院

@Dao
public interface FavoriteMovieDao {
    @Query("SELECT * FROM favoritemovie")
    List<FavoriteMovie> getAll();

    @Query("SELECT * FROM favoritemovie WHERE id IN (:ids)")
    List<FavoriteMovie> loadAllByIds(int[] ids);

    @Query("SELECT * FROM favoritemovie WHERE id LIKE :id LIMIT 1")
    FavoriteMovie findById(int id);

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    void insert(FavoriteMovie movie);

    @Delete
    void delete(FavoriteMovie movie);
}

FavoriteMovie.java(实体)

@PrimaryKey
private int id;
public int getId(){
    return id;
}

public void setId(int id){
    id = id;
}

@ColumnInfo(name = "favorite")
private boolean favorite;

public boolean getFavorite(){
    return favorite;
}

public void setFavorite(boolean favorite){
    favorite = favorite;
}

public void FavoriteMovie(int id, boolean favorite) {
    this.id = id;
    this.favorite = favorite;
}

尝试执行查询,然后执行插入

db = Room.databaseBuilder(getApplicationContext(),
AppDatabase.class, "database-name").allowMainThreadQueries().build();
if (db.favoriteMovieDao().findById(classId) == null) {
    FavoriteMovie fm = new FavoriteMovie();
    fm.setId(classId);
    fm.setFavorite(true);
    db.favoriteMovieDao().insert(fm);
}

AppDatabase.java

@Database(entities = {FavoriteMovie.class}, version = 1)
public abstract class AppDatabase extends RoomDatabase {
    public abstract FavoriteMovieDao favoriteMovieDao();
}

1 个答案:

答案 0 :(得分:1)

您的setId方法未引用字段id。您的参数遮盖了您的字段。我认为您应该改用this.id