1 回答
TA贡献1830条经验 获得超9个赞
现在是我想问的主要问题。我将向您展示我的代码,也许您会明白为什么不能正常工作。
我相信您的问题是,当您插入 AudioFile 时,未设置 id,因此 AudioFile 对象 audioFile 中的 id 为 0。但是,插入时,id 将自动生成,并且不会为 0,而可能是某个时间插入的 AudioFile 对象的数量 + 1。
如果不设置id,则使用相同的 AudioFile 对象来更新/删除将尝试使用0的 id 来更新删除。不会有这样的行。
假设AudioFile 存在setId方法,但不处理失败的插入,可以使用以下修复:-
audioFile.setId(audioFileDao.insertAudioFile(audioFile));
可以处理未导致异常的失败插入的修复可能是:-
long insertedId = audioFileDao.insertAudioFile(audioFile);
if (insertedId > 0) {
audioFile.setId(insertedId);
} else {
//......... handle not inserted
}
示例/演示
以下代码运行时显示上述内容(您的 Entity 和 Dao 已按原样复制):-
...... database built
mAudioFileDao = mAppDB.audioFileDao();
AudioFile a = new AudioFile();
a.setTitle("MySong");
a.setDuration(5);
a.setArtist("Fred");
a.setPath("/thepath");
logAudioFile(a,"Before Insert into DB");
long currentId = mAudioFileDao.insertAudioFile(a); //<<<<<<<<<< INSERT INTO DB
logAudioFile(a,"Immediately after Insert. ID returned from insert is " + currentId);
a.setId(currentId); //<<<<<<<<<< SET the the id of the AudioFile object a
logAudioFile(a,"After setting the ID to " + currentId);
mAudioFileDao.updateAudioFile(a);
List<AudioFile> audioFileList = mAudioFileDao.getAll();
for (AudioFile af: audioFileList) {
logAudioFile(af,"Extracted from DB");
}
mAudioFileDao.deleteAudioFile(a);
Log.d("AUDIOFILEINFO","Attempt to delete Audio File undertaken");
audioFileList = mAudioFileDao.getAll();
for (AudioFile af: audioFileList) {
logAudioFile(af,"After deletion");
}
logAudioFile方法是: -
private void logAudioFile(AudioFile a, String extra) {
Log.d(
"AUDIOFILEINFO",
"Title is " + a.getTitle() +
" ID is " + a.getId() +
"\n\tExtra Info is " + extra
);
}
结果(上面的日志):-
2019-10-06 11:03:39.757 D/AUDIOFILEINFO: Title is MySong ID is 0
Extra Info is Before Insert into DB
2019-10-06 11:03:39.808 D/AUDIOFILEINFO: Title is MySong ID is 0
Extra Info is Immediately after Insert. ID returned from insert is 1
2019-10-06 11:03:39.808 D/AUDIOFILEINFO: Title is MySong ID is 1
Extra Info is After setting the ID to 1
2019-10-06 11:03:39.829 D/AUDIOFILEINFO: Title is MySong ID is 1
Extra Info is Extracted from DB
2019-10-06 11:03:39.831 D/AUDIOFILEINFO: Attempt to delete Audio File undertaken
您对房间有何看法?
这是征求意见,所以是题外话。
添加回答
举报