【问题标题】:Async Task reset the List to null when using runOnUiThread使用 runOnUiThread 时,异步任务将列表重置为空
【发布时间】:2014-05-12 09:50:15
【问题描述】:
    @Override
    protected List<String> doInBackground(String... urls) {

        JPOSeReprintPreview.this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                myReceipt reprintReceipt = new myReceipt ();
                lstOutput= reprintReceipt.saveReprint(muncID);

                if(lstOutput.size()==0 || lstOutput==null){
                    System.out.println("Failed Sending data");
                }
            }
        });
        return lstOutput;
    }


 @Override
        protected void onPostExecute(List<String> response) {
                if(response.get(0).equals("SUCCESS")){  }  }

我的列表 lstOutput 在访问 onPostExecute 时重置为 null。我的 onPostExecute 出现无效索引异常。为什么会发生这种情况?

【问题讨论】:

    标签: java android asynchronous android-asynctask


    【解决方案1】:
    • 您在doInBackground() 中将Runnable 发布到UI Thread,这导致AsyncTask 毫无意义。
    • lstOutput 在更新之前被重新调整,因此它始终为空。
    • 如果调用size() 时为空,if (lstOutput.size() == 0 || lstOutput == null) 将崩溃。应该首先检查 null。

    您的代码的意图尚不清楚,但您可能应该这样做

    private final  myReceipt reprintReceipt;
    
    public AsyncTaskName() {
        myReceipt reprintReceipt = new myReceipt();
    }
    
    @Override
    protected List<String> doInBackground(String... urls) {
        return reprintReceipt.saveReprint(muncID);
    }
    
    
    @Override 
    protected void onPostExecute(List<String> response) {
        if (response == null || response.isEmpty()){
            System.out.println("Failed Sending data");
            return;
        }
    
        if(response.get(0).equals("SUCCESS")){
        }
    }
    

    编辑:如果Handler 是在myReceipt() 构造函数中创建的,则将其创建移动到onPreExecute()AsyncTasks 构造函数(如果它是从UI 线程调用的)。 无论如何,如果 myReceipt.saveReprint() 方法在 AsyncTask 中执行,则不应使用 Handler,因此您的设计完全有问题。

    【讨论】:

    • 我使用服务处理程序来处理我的 reprintReceipt.saveReprint(muncID);这就是为什么我添加了 JPOSeReprintPreview.this.runOnUiThread(new Runnable()... 我不能使用它在运行时给出错误的方法(无法在线程内创建处理程序)
    猜你喜欢
    • 2020-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-16
    • 1970-01-01
    • 2014-03-19
    • 2014-12-10
    相关资源
    最近更新 更多