我正在尝试使用房间库的简单数据库示例。 我有一个报警类
@Entity
public class Alarm{
@PrimaryKey
public int id;
public long alarmtime;
public Alarm(int id, long alarmtime){
this.id = id;
this. alarmtime = alarmtime;
}
}
AlarmDAO界面,
@Dao
public interface AlarmDAO {
@Insert(onConflict = OnConflictStrategy.REPLACE)
void addAlarm(Alarm alarm);
@Query("select * from Alarm")
public List<Alarm> getAllAlarm();
@Query("select * from Alarm where id = :id")
public List<Alarm> getAlarm(long userId);
@Update(onConflict = OnConflictStrategy.REPLACE)
void updateAlarm(Alarm alarm);
@Query("delete from Alarm")
void removeAllAlarm();
}
一个AlarmDatabase类,
@Database(entities = {Alarm.class}, version = 16, exportSchema = false)
public abstract class AlarmDatabase extends RoomDatabase {
private static AlarmDatabase INSTANCE;
public abstract Alarm AlarmDAO();
public static AlarmDatabase getDatabase(Context context) {
if (INSTANCE == null) {
INSTANCE =
Room.databaseBuilder(context, AlarmDatabase.class, "userdatabase")
.allowMainThreadQueries()//remove this line in production
.fallbackToDestructiveMigration()
.build();
}
return INSTANCE;
}
}
在我尝试从AlarmDAO访问方法的MainActivity中,它说它无法解析方法,
database = AlarmDatabase.getDatabase(this);
database.AlarmDAO().removeAllAlarm();
答案 0 :(得分:2)
AlarmDao
中没有名为AlarmDatabase
的字段。您有一个名为AlarmDAO()
的方法。因此,请调用AlarmDAO()
方法:
database.AlarmDAO().removeAllAlarm();
答案 1 :(得分:0)
在分析了我的所有代码后,我意识到我曾使用AlarmDAO
分配给Alarm
(我不知道为什么可以接受,因为它们的类型不同)所以在AlarmDatabase.java使它开始工作。
@Database(entities = {Alarm.class}, version = 16, exportSchema = false)
public abstract class AlarmDatabase extends RoomDatabase {
private static AlarmDatabase INSTANCE;
public abstract AlarmDAO AlarmDAO();// WAS originally Alarm AlarmDAO();
public static AlarmDatabase getDatabase(Context context) {
...