Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AsyncTask return List to Activity

how do I return a List generated in an AsyncTask back to the Activity?

My LoadStringsAsync class:

public class LoadStringsAsync extends AsyncTask<Void, Void, List<String> > {

    List<String> str;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        ...
    }

    @Override
    protected List<String> doInBackground(Void... arg0) {
        ...
        get content from the internet
        and
        fill the list
        ...
    }

    @Override
    protected void onPostExecute(List<String> str) {
        super.onPostExecute(events);
        ...

    }
}

and I need the List back in my Activity to work with it. (No not only to show it in ListView :P)

Any suggestions how to do this? :-)

Thanks so far!

like image 905
Heisnberg Avatar asked Jul 11 '13 14:07

Heisnberg


1 Answers

your Activity:

public class YourActivity extends Activity {
    private List<String> list = new ArrayList<String>();

    public void onCreate(Bundle state) {
        //...
    }

    public void setList(List<String> list) {
        this.list = list;
    }

    private void fireYourAsyncTask() {
        new LoadStringsAsync(this).execute();
    }

}    

AsyncTask:

public class LoadStringsAsync extends AsyncTask<Void, Void, List<String>> {

    List<String> str;
    private YourAcitivity activity;

    public LoadStringsAsync(YourAcitivity activity) {
        this.activity = activity;
    }

    @Override
    protected List<String> doInBackground(Void... arg0) {
    }

    @Override
    protected void onPostExecute(List<String> str) {
        super.onPostExecute(events);
        activity.setList(str);
    }
}
like image 61
wtsang02 Avatar answered Oct 05 '22 06:10

wtsang02