use*_*865 3 database android callable android-room
没有太多文档可以了解 runInTransaction() 方法到底如何工作。在不同的 DAO 上执行多个操作时,如果不返回任何值,我可以使用runInTransaction(Runnable body)ORrunInTransaction(Callable<V> body)如果要返回任何结果,
我的查询: 如果事务中的所有查询都成功,那么我想返回一个图像对象,需要在事务成功时将其上传到服务器如果发生任何异常或事务不成功,我需要返回一个布尔值false 指示用户发生了某些错误。
方法如下:
public boolean userCheckedIn(final User user) {
try {
appDatabase.runInTransaction(new Callable<Object>() {
@Override
public Object call() throws Exception {
if (user != null) {
//Add entry in table A
appDatabase.UserDao().add(user);
//Update entry in table B
//Delete an entry from table C
Event image = updateUserAction(action);
return image;
}
return null;
}
});
} catch (Exception e) {
return false;
}
return true;
}
Run Code Online (Sandbox Code Playgroud)
在上面的方法中,我打算做的是,如果所有数据库执行都成功,我需要返回一个将上传到服务器的图像。如果在执行数据库事务时发生任何异常或发生任何错误,我需要返回false以让用户知道发生了错误。不确定我是否做对了。另外,我应该将 runInTransaction 放在 try catch 块中吗?
的代码runInTransaction(Callable)相当于以下runInTransaction(Runnable)版本:
setTransactionSuccessful(),否则将被视为失败并将回滚)。Callable如果在or内部引发异常Runnable,则不会处理该异常(在Callable这种情况下,但会重新引发)。这意味着您需要在调用 或 的代码中处理runInTransaction(Callable)它runInTransaction(Runnable)。主要功能区别在于runInTransaction(Callable)返回Callable.
所以,你的代码可以做两件事:
null,并在调用userCheckedIn(User)或的方法中上传图像,userCheckedIn(User)在您的方法中上传图像第二个解决方案(鉴于我没有调用方法的代码,我更容易向您展示代码userCheckedIn(User))将类似于此:
public boolean userCheckedIn(final User user) {
try {
Event image = appDatabase.runInTransaction(new Callable<Object>() {
@Override
public Object call() throws Exception {
if (user != null) {
//Add entry in table A
appDatabase.UserDao().add(user);
//Update entry in table B
//Delete an entry from table C
Event image = updateUserAction(action);
return image;
}
return null;
}
});
if (image != null) {
// Upload the image to the server
} else {
// No image available (probably because of the "if (user != null)"
// inside Callable). I assume you want to return false in this case.
return false;
}
} catch (Exception e) {
return false;
}
return true;
}
Run Code Online (Sandbox Code Playgroud)