0

I have an asynctask and inside doInBackground, I don't have a for/while loop. Instead, I have a different class for it and that class generates a list using a for loop. So how can I update UI with onProgressUpdate?

Here is:

@Override
protected List<MyObject> doInBackground(Void... voids) {
    IAppLogic appLogic = new AppLogic(mContext);
    List<MyObject> list =  appLogic.getApps(ALL_APPS);

    return list;
}

MyObject is a custom object and IAppLogic is the interface of the class that gets installed applications.

1 Answers1

0

You can implement this by giving the getApps()-method a callback-parameter. Pseudo code:

interface AppFoundCallback {
    public onAppFound(App app, int progress);
}

// in AppLogic.getApps:
public getApps(String filter, AppFoundCallback callback)
    for (int i = 0; i < listOfApps.length; i++) {
        // Do the work you need to do here.
        int progress = (i / listOfApps.length) * 100;
        callback.onAppFound(app, progress);
    }
}

// in your Task:
class Task extends AsyncTask implements AppFoundCallback {

    // Implement the callback
    @Override
    onAppFound(App app, int progress) {
        this.publishProgress(progress);    
    }

    // Setup and register the listener
    @Override
    protected void doInBackground() {
        // Ohter stuff
        List<MyObject> list =  appLogic.getApps(ALL_APPS, this);
    }

    // Render progress updates on the UI
    @Override
    protected void onProgressUpdate(Integer... progress) {
        progressView.setProgress(progress[0]);
    }    

}

Simply put: your code notifies the caller of the getApps()-method every time you find something. This will then be published as a progress-update. The publishProgress()-method is part of AsyncTask and will take care of calling onProgressUpdate() on the UI-Thread, so that you can simply update your views.

Lukas Knuth
  • 25,449
  • 15
  • 83
  • 111