我是Room的新手,更新数据库时遇到了一些问题。插入和删除工作正常,但是更新不起作用。数据库中的数据保持不变。我尝试使用整个对象和@Query语句中的特定字段进行更新。我做错了什么?
实体:
@Entity(tableName = "Appointments")
public class Appointment {
@PrimaryKey
@NonNull
public int AppointmentID;
public Boolean CheckInStatus;
public Appointment(
@NonNull int AppointmentID,
Boolean CheckInStatus
) {
this.AppointmentID = AppointmentID;
this.CheckInStatus = CheckInStatus;
}
public void setCheckInStatus(Boolean checkInStatus) {
CheckInStatus = checkInStatus;
}
@NonNull
public int getAppointmentID() {
return this.AppointmentID;
}
public Boolean getCheckInStatus() {
return CheckInStatus;
}
public void setID(@NonNull int AppointmentID) {
this.AppointmentID = AppointmentID;
}
Dao:
@Update
void update(Appointment appointment);
@Query("UPDATE Appointments SET CheckInStatus = 1 WHERE AppointmentID = :Id")
void updateCheckIn(int Id);
代码库:
public void updateCheckIn(int Id) {
new AppointmentRepository.updateCheckInAsyncTask(mAppointmentDao, Id);
}
public static class updateCheckInAsyncTask extends AsyncTask<Void, Void, Void> {
private AppointmentDao mAsyncTaskDao;
private int mId;
updateCheckInAsyncTask(AppointmentDao dao, int Id) {
mAsyncTaskDao = dao;
mId = Id;
}
@Override
protected Void doInBackground(Void... voids) {
mAsyncTaskDao.updateCheckIn(mId);
return null;
}
}
public void update(Appointment appointment) {
new AppointmentRepository.updateAsyncTask(mAppointmentDao, appointment);
}
private static class updateAsyncTask extends AsyncTask<Void, Void, Void> {
private AppointmentDao mAsyncTaskDao;
private Appointment mAppointment;
updateAsyncTask(AppointmentDao dao, Appointment appointment) {
mAsyncTaskDao = dao;
mAppointment = appointment;
}
@Override
protected Void doInBackground(Void... voids) {
mAsyncTaskDao.update(mAppointment);
return null;
}
}
视图模型:
public void update(Appointment appointment) { mRepository.update(appointment); }
public void updateCheckIn(int Id) { mRepository.updateCheckIn(Id); }
活动:
// Update check in status in table
mAppointmentVM.updateCheckIn(mId);
当我使用这种方式时,正确的id和更新后的对象都被传递了。非常感谢您的帮助。
编辑: 最终答案是:
public void updateCheckIn(int Id) {
new AppointmentRepository.updateCheckInAsyncTask(mAppointmentDao, Id).execute();
}
public static class updateCheckInAsyncTask extends AsyncTask<Void, Void, Void> {
private AppointmentDao mAsyncTaskDao;
private int mId;
updateCheckInAsyncTask(AppointmentDao dao, int Id) {
mAsyncTaskDao = dao;
mId = Id;
}
@Override
protected Void doInBackground(Void... voids) {
Appointment entity = mAsyncTaskDao.getAppointmentDetails(mId);
entity.setCheckInStatus(true);
mAsyncTaskDao.update(entity);
return null;
}
}
@Update(onConflict = OnConflictStrategy.REPLACE)
这对我很有效。 - Mohd Qasim