How to pass more values in the doInBackground
My AsyncTask
looks like this.
private class DownloadFile extends AsyncTask<String, Integer, String> {
@Override
protected String doInBackground(String... sUrl) {
{
}
}
Is it possible somehow to pass more values on my protected String DoInBackground
for example: protected String doInBackground(String... sUrl, String... otherUrl, Context context)
And how to execute
the AsyncTask
after? new DownloadFile.execute("","",this)
or something?
new DownloadFile().execute("my url","other parameter or url");
private class DownloadFile extends AsyncTask<String, Integer, String> {
@Override
protected String doInBackground(String... sUrl) {
{
try {
return downloadContent(sUrl[0], sUrl[1]); // call
} catch (IOException e) {
return "Unable to retrieve data. URL may be invalid.";
}
}
}
you can do something like this inside your doInBackground method:
String a = sUrl[0]
String b = sUrl[1]
execute AsyncTask in this way:
new DownloadFile().execute(string1,string2);
the first value : sUrl[0] will be the one passed from string1 and
surl[1] will be the second value passed i.e string2 !
you can send multiple parameters as you can send them as varargs. But you have to use same Type of parameter. So to do what you are trying you can follow any of the followings
Option 1
you can use a setter method to set some value of the class member then use those in doInBackGround. For example
private class DownloadFile extends AsyncTask<String, Integer, String> {
private Context context;
public void setContext(Context c){
context = c;
}
@Override
protected String doInBackground(String... sUrl) {
{
// use context here
}
}
Option 2
Or you can use constructor to pass the values like
private class DownloadFile extends AsyncTask<String, Integer, String> {
private Context context;
public DownloadFile (Context c){
context = c;
}
@Override
protected String doInBackground(String... sUrl) {
{
// use context here
}
}
String... sUrl
the three consecutive dots meaning more then one String. The dots are varargs
And how to pass the Context?
you can force it adding a constructor that takes the Context as parameter:
private Context mContext;
public void setContext(Context context){
if (context == null) {
throw new IllegalArgumentException("Context can't be null");
}
mContext = context;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With