java - 使用 runOnUiThread 时,异步任务将 List 重置为 null

标签 java android asynchronous android-asynctask

    @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")){  }  }

My list lstOutput Reset to null when accessing the onPostExecute.. im having invalid index exception at my onPostExecute.. why this is happening?

最佳答案

  • 您将Runnable发布到doInBackground()中的UI线程,这会导致毫无意义的AsyncTask。<
  • lstOutput 在更新之前会重新调整,因此它始终为 null。
  • if (lstOutput.size() == 0 || lstOutput == null) 如果调用 size() 时为 null,将会崩溃。应首先检查 null。

您的代码的 Intent 尚不清楚,但您应该这样做

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,因此您的设计完全错误。

关于java - 使用 runOnUiThread 时,异步任务将 List 重置为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23605856/

相关文章:

java - Android Room-插入之前如何检查同名实体?

java - 如何处理自定义HandlerMethodArgumentResolver抛出的异常?

java - 如何为数组列表中的用户分配属性?

android - 使用 java.io.IOException 不生成测​​试覆盖率报告

C++同时输入输出到控制台窗口

javascript - 如何将数据传递给外部 javascript 脚本并异步加载

asynchronous - Ada 中的触发和忘记进入/接受机制

java - JsonGenerationException : CSV generator does not support Object values for properties

android - 为没有回调的传感器创建循环程序?

安卓相机黑屏