我正在制作一个警报应用程序,我将编写一个查询来切换一些警报属性,这是我的警报类。
@Entity
data class Alarm(
val label: String?,
var isEnabled: Boolean,
val ringTime: LocalTime,
val occursOn: MutableSet<Day>,
var isVibrationEnabled: Boolean,
@PrimaryKey(autoGenerate = true) var id: Int? = null
)
这是我的查询,应该反转振动值
@Query("UPDATE Alarm SET isVibrationEnabled = NOT isVibrationEnabled WHERE id = :alarmId")
internal abstract fun toggleVibration(alarmId: Int): Completable
该应用程序编译正常,因此该查询似乎有效,但是在我执行该查询后,该值未反转并且保持不变
答案 0 :(得分:1)
我相信您的问题不是切换,而是有效。
问题在于, WHERE子句未选择行(或预期的行),因此,在调用< strong> toggleVibration 功能不是警报的ID 或预期的警报。
考虑以下示例(为了方便起见,使用Java而不是Kotlin):-
AlarmEntity Alarm.java
public class Alarm {
@PrimaryKey(autoGenerate = true)
private long id;
private String label;
private boolean isEnabled;
private boolean isVibrationEnabled;
public Alarm() {
}
public Alarm(String label, boolean isEnabled, boolean isVibrationEnabled) {
this.label = label;
this.isEnabled = isEnabled;
this.isVibrationEnabled = isVibrationEnabled;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
public boolean isEnabled() {
return isEnabled;
}
public void setEnabled(boolean enabled) {
isEnabled = enabled;
}
public boolean isVibrationEnabled() {
return isVibrationEnabled;
}
public void setVibrationEnabled(boolean vibrationEnabled) {
isVibrationEnabled = vibrationEnabled;
}
}
AlarmDao.java
@Dao
public interface AlarmDao {
@Insert
long[] insertAlarm(Alarm... alarms);
@Insert
long insertAlarm(Alarm alarm);
@Query("SELECT * FROM Alarm")
List<Alarm> getAllAlarms();
@Query("UPDATE Alarm SET isVibrationEnabled = NOT isVibrationEnabled WHERE id = :id")
int toggleVibration(long id);
}
活动代码以进行测试:-
alarmDao = mDB.getAlarmDao();
// Add a copule of alarms
alarmDao.insertAlarm(
new Alarm("Alarm001",true,true),
new Alarm("Alarm002",false,false)
);
// Get the Alarms and output them to the log
List<Alarm> myalarms = alarmDao.getAllAlarms();
for (Alarm a: myalarms) {
Log.d("ALARMBEFORE","Label = " + a.getLabel() + " Enabaled = " + String.valueOf(a.isEnabled()) + " Vibration = " + a.isVibrationEnabled());
}
//<<<<<<<<<< Toggle the first alarm >>>>>>>>>>
alarmDao.toggleVibration(myalarms.get(0).getId());
// Again get all the alarams and output them to the log
myalarms = alarmDao.getAllAlarms();
for (Alarm a: myalarms) {
Log.d("ALARMAFTER","Label = " + a.getLabel() + " Enabaled = " + String.valueOf(a.isEnabled()) + " Vibration = " + a.isVibrationEnabled());
}
05-30 10:34:33.853 D/ALARMBEFORE: Label = Alarm001 Enabaled = true Vibration = true 05-30 10:34:33.853 D/ALARMBEFORE: Label = Alarm002 Enabaled = false Vibration = false 05-30 10:34:33.856 D/ALARMAFTER: Label = Alarm001 Enabaled = true Vibration = false 05-30 10:34:33.856 D/ALARMAFTER: Label = Alarm002 Enabaled = false Vibration = false
即对于Alarm001,isVibrationEnabaled值已从true切换为 false