首页 > 解决方案 > 等待 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 比较陌生,这是我第一次遇到同步问题。也许解决方案很简单,我只是做错了什么。任何帮助深表感谢

标签: javaandroidmultithreadingnestedsynchronization

解决方案


推荐阅读