Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I pass different types of parameters to an AsyncTask in Android?

I want to implement a generic, thread save class which takes the RessourceId of an ImageView and the Url (http) where the desired image file is stored. It'll download the image and fills the src of the ImageView in the UiThread.

I thought AsyncTask would be the best thing for me. However I noticed that I only can pass one type of parameters to the doInBackground() Method. Like an Array of Urls. Is that true? What would u suggest me?

like image 914
OneWorld Avatar asked Oct 13 '10 08:10

OneWorld


2 Answers

You can pass params as objects

new MyTask().execute(url, str, context);

public class MyTask extends AsyncTask<Object, Void, Void> {
    @Override
    protected Void doInBackground(Object... params) {
            Url url = (Url) params[0];
            String str = (String) params[1];
            Context ctx = (Context) params[2];

            return null;
    }
}
like image 153
garmax1 Avatar answered Nov 14 '22 23:11

garmax1


You can add setter methods to your AsyncTask implementation, or even define your own constructor to pass additional parameters.

Optionally, if your AsyncTask implementation is an inner class of an activity you can access all the instance variables of your activity. I prefer the above option myself, as it clearly indicates which data the task requires.

like image 36
hpique Avatar answered Nov 14 '22 21:11

hpique