简体   繁体   中英

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

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

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.

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 .

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]);
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM