java - 等待 SingleThreadExecutor 在继续 UI 线程执行之前将结果传递给 UI 线程 (RunOnUIThread)。安卓
问题描述
我正在使用 android Room,并且我有一个布尔方法,它通过 Executor 查询数据库以查看用户提供的 ID 是否已被使用。一切正常,但有时来自 DB 调用的应答器到达主线程的时间很晚,这意味着我的代码不知道 id 是新的还是旧的。我想让方法中的代码等到执行器中的 runOnUiThread 为该方法的其余部分提供了结果才能使用。
//check id validity with two different error messages
int isNew=-1;
void setIsNewId(int result){
isNew=result;
}
private boolean checkId(){
String id=mId.getText().toString().trim();
try{
final int parseId=Integer.parseInt(id);
AppExecutors.getInstance().diskIO().execute(new Runnable() {
@Override
public void run() {
final int result=mDb.clientDao().isIdNew(parseId);
runOnUiThread(new Runnable() {
@Override
public void run() {
setIsNewId(result);//<--THIS ARRIVES TOO LATE TO MAIN THREAD
}
});
}
});
//THIS SHOULD WAIT UNTIL RESULT IS AVAILABLE
if (isNew==1 && !id.isEmpty()){
ilId.setErrorEnabled(false);
return true;
}else if(isNew==0){
ilId.setErrorEnabled(true);
ilId.setError("Id has to be new");
mId.setError("Id needs to be new");
Toast.makeText(this,"Id needs to be new", Toast.LENGTH_LONG).show();
return false;
}else{
Toast.makeText(this,"its taking too long", Toast.LENGTH_LONG).show();
return false;
}
}catch(Exception e){
ilId.setErrorEnabled(true);
ilId.setError("Id has to be numeric");
mId.setError("Id has to be numeric");
Toast.makeText(this,"Id needs to be numeric", Toast.LENGTH_LONG).show();
return false;
}
}
我已经尝试过使用互斥锁、CountDownLatch、睡眠调用对对象进行同步。但似乎都冻结了我的 UI 并使我的应用程序崩溃。我知道执行程序有一个 submit() 方法,但我还没有找到一个关于如何在我的嵌套线程上下文中使用它的示例。我对 android 比较陌生,这是我第一次遇到同步问题。也许解决方案很简单,我只是做错了什么。任何帮助深表感谢
解决方案
推荐阅读
- java - Chrome 无头浏览器不适用于特定网站
- amazon-web-services - 查看/分析我存储在 S3 存储桶中的指标有哪些好的策略/应用程序?
- csv - 使用宏在 MSAccess 中导入大量 csv
- vb.net - 在列表框 VB.net 上排序名称
- .net - 启动新的 react-native 项目时找不到 .Net 核心
- javascript - 尝试使用 JavaScript 将 css 样式添加到 iframe
- sql - 不同字段上的 SQL 案例,具有不同的数据可用性
- python - ModuleNotFoundError:没有名为“mysite.apps”的模块
- python - 自定义 JSON 编码器引发“对象不可序列化 JSON”错误
- sql - 有没有办法改进这个查询