I have created an AsyncTask which read JSONArray in the doInBackground Method and return an ArrayList of custom Items (ArrayList). Before this, in the onPostExecute method i move the ArrayList charged in the AsyncTask to another ArrayList of the Main thread, but i think that my AsyncTask never ends and still working. Here I put my code:
Here the 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
}
}
Here the call to the AsyncTask in the Main Thread:
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());
}
}
In the log i see that all Log in the onPostExecute() method are printed, but nothing from the Main Thread.
I don’t know where is the error to fix it, i have been working on it 2 days and searching in forums, here in StackOverflow and i can’t fix that :S
As name indicates
AsyncTaskis asynchronous, but you for some reason expectsexecute()to be blocked unless async task ends, which is wrong. Your code works fine and I expect listMain to simply be empty and onceexecute()fires asynctask,forwould show nothing because async task is not done yet. You should rework your app logic, so async task could tell “main thread” it finished. I.e. move yourforloop to separate method and call it fromonPostExecute().