How do I change (String ...params) argument list in doInBackground asyncTask in android?

2.4k Views Asked by At

by default from api for asyncTask the signature for it is doInBackground(Param ...params)

in my app I have this signature:

public String doInBackground(String ...params) 

I tried and changed to this:

public String doInBackground(String param, int x) 

but it gives me error:

class DataTasker must be declared abstract or implement abstract method 'doInBackground(Params...params)

I know this 3 dots is an array and i can access it like

params[0] , params[1].

But still confused, in my main activity class I want to pass this data for background task: a string , an integer

DataTasker data = new DataTasker() ;
data.execute("mister x " , 56) ;

But apparently, i must pass only one argument

4

There are 4 best solutions below

0
On BEST ANSWER

You can try ,

Convert the integer into String and pass it wih the "mister x"

DataTasker data = new DataTasker() ;
data.execute("mister x " , String.valueOf(56)) ;

You can access both values as params and convert the second parameters into integer again

@Override
protected JSONObject doInBackground(String... params) {

    String user=params[0];
    int value = Integer.parseInt(params[1]);
}
0
On

I believe you can use Object instead of String and then it iwll look like public String doInBackground(Object ...params). And you also will have to cast params[0] , params[1] to needed you types.

0
On

But apparently, i must pass only one argument

No, you can pass as many as you want. They all have to be the same base type.

Some options:

  1. Declare the type as Object. This will require lots of casts.

  2. Declare the type as String, pass in a String representation of your int, and convert it back later on.

  3. Pass one or the other parameter via a DataTasker constructor.

  4. Pass one or the other parameter via a setter on your DataTasker.

0
On

One thing you can do is create an extension of AsyncTask where the desired parameter for the doInBackground is an Object. Something like this:

 private class DataTasker extends AsyncTask<Object, Void, String>

This way you can do your parameter casting inside the doInBackground method.