【问题标题】:AsyncTask never ends in onPostExecute methodAsyncTask 永远不会在 onPostExecute 方法中结束
【发布时间】:2012-11-10 15:48:32
【问题描述】:

我创建了一个 AsyncTask,它在 doInBackground 方法中读取 JSONArray 并返回自定义项 (ArrayList) 的 ArrayList。在此之前,在 onPostExecute 方法中,我将 AsyncTask 中的 ArrayList 移动到主线程的另一个 ArrayList,但我认为我的 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

【问题讨论】:

    标签: android android-asynctask


    【解决方案1】:

    顾名思义,AsyncTask异步的,但出于某种原因,您希望 execute() 被阻塞,除非异步任务结束,这是错误的。您的代码工作正常,我希望 listMain 简单地为空,并且一旦 execute() 触发 asynctask,for 将不会显示任何内容,因为异步任务尚未完成。您应该重新设计您的应用程序逻辑,以便异步任务可以告诉“主线程”它完成了。 IE。将您的 for 循环移动到单独的方法并从 onPostExecute() 调用它。

    【讨论】:

    • 我已经改进了 Asynctask 的另一种算法,现在它可以工作了,谢谢你教我这一课,这是我的第一个 AsyncTask,我没有正确的方法。谢谢:)
    猜你喜欢
    • 1970-01-01
    • 2011-05-28
    • 1970-01-01
    • 2013-11-07
    • 2016-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-17
    相关资源
    最近更新 更多