AsyncTask永远不会以onPostExecute方法结束

时间:2012-11-10 15:48:33

标签: android android-asynctask

我创建了一个AsyncTask,它在doInBackground方法中读取JSONArray并返回自定义Items(ArrayList)的ArrayList。在此之前,在onPostExecute方法中,我将AsyncTask中收取的ArrayList移动​​到Main线程的另一个ArrayList,但我认为我的AsyncTask永远不会结束并且仍在工作。在这里,我把我的代码:

这里是AsyncTask:

private class ReadJSONTask extends AsyncTask<Void, Void, ArrayList<Item>>{

        @Override
        protected ArrayList<Item> doInBackground(Void... params) {
            // TODO Auto-generated method stub
            ArrayList<Item> auxList = new ArrayList<Item>();
            LoadData(auxList); //Method that reads JSON and load information in the ArrayList
            return auxList; // Return ArrayList
        }

        @Override
        protected void onPostExecute(ArrayList<Item> result) {
            // TODO Auto-generated method stub

            Log.i("OnPostExecute", String.valueOf(result.size()));  //The size of the array
            listMain = result; // Move the data of the AsyncTask to the main Thread

            Log.i("OnPostExecute", String.valueOf(listaComic.size()));  //The size of the ArrayList I use in the Main Thread
        }

    }

这里调用主线程中的AsyncTask:

if (isOnline()){    //Return true if there is internet connection
    ReadJSONTask task = new ReadJSONTask();
    task.execute();

    Log.i("Main Thread - listMain Size", String.valueOf(listMain.size())); //Never executed

    //This for loop its only for debug purposes, never executed
    for (Item item : listMain){ 
        Log.i("Items", item.toString());
    }
}

在日志中我看到所有登录onPostExecute()方法都是打印的,但是没有来自主线程。

我不知道修复它的错误在哪里,我已经工作了2天并在论坛中搜索,在StackOverflow这里我无法修复:S

1 个答案:

答案 0 :(得分:4)

由于名称表明AsyncTask 异步,但由于某种原因,您希望阻止execute(),除非异步任务结束,这是错误的。你的代码运行正常,我希望listMain只是空的,一旦execute()触发asynctask,for就不会显示任何内容,因为异步任务还没有完成。您应该重新设计您的应用程序逻辑,因此异步任务可以告诉“主线程”它已完成。即将您的for循环移至单独的方法,并从onPostExecute()调用它。