code is working laggy in postExecute but won't work in doInBackground?

55 views Asked by At

I am fetching album art with the last.fm api in an asynctask class. The code works in postExecute() with latency, though it won't work at all in doInBackground().. it is not making updates to my UI at all, so i'm not sure what's going on

@Override
public Void doInBackground(String... args){

    if(oslist.size()!=0) {
        for (int i = 0; i < 30; i++) {

            String albumURL = null;

            try{
                 albumURL = new RetrieveAlbumArtUrlTask().execute(String.format(APIURL,
                         URLEncoder.encode(oslist.get(i).get(TAG_ARTIST), "UTF-8"),
                         URLEncoder.encode(oslist.get(i).get(TAG_ALBUM), "UTF-8"))).get();


            } catch (UnsupportedEncodingException e) {

            } catch (InterruptedException e) {

            } catch(ExecutionException e){

            }

            oslist.get(i).put("albumArtUrl", albumURL);
            Log.v("TEST", ""+albumURL);

        }
    }

    return null;
}
2

There are 2 answers

0
Itzik Samara On

you have 2 choices : 1. return the data you want to update to the onPostExecute and update the UI from there.. dont do long operation on the postExecute.. 2.if your running this on the Activity Class you can use the RunOnUIThread function inside the doInBackground and update the UI from it.

0
Jay Snayder On

An AsyncTask does not work in that manner Teddy. The AsyncTask is broken up into two parts. The doInBackground() segment is meant to handle non-UI components because it works outside the UI thread. When you need to make a change to UI from within the AsyncTask, you call publishProgress() with a custom identifier to distinguish what you want updated.

I often do this with an enum. Then you shall see your UI changes occurring and your non-UI components from lagging the UI. Just read up on the AsyncTask examples a bit.