Home » Android » java – How can I pass a primitive int to my AsyncTask?

java – How can I pass a primitive int to my AsyncTask?

Posted by: admin June 15, 2020 Leave a comment

Questions:

What I want it’s to pass one int variable to my AsyncTask.

int position = 5;

And I declared my AsyncTask like this:

class proveAsync extends AsyncTask<int, Integer, Void> {

    protected void onPreExecute(){
    }

    protected Void doInBackground(int... position) {
    }

    .
    .
    .

But I got an error that it’s the following:

Type argument cannot be of primitive type

I just could pass an int[] and Integer variables but never an int variable and I execute my AsyncTask like this:

new proveAsync().execute(position);

Is there something that I could do to pass only this position?

Thanks in advance!

How to&Answers:

Pass your parameter as Integer

class proveAsync extends AsyncTask<Integer, Integer, Void> {

    protected void onPreExecute(){
    }

    protected Void doInBackground(Integer... position) {
        int post = position[0].intValue();
    }

    .
    .
    .

while executing do this

new proveAsync().execute(new Integer(position));

You can get the int value in AsyncTask as using intValue()

Answer:

Use it like this.

class proveAsync extends AsyncTask<Integer, Void, Void> {

    protected void onPreExecute(){
    }

    protected Void doInBackground(Integer... params) {
        int position = params[0];
    ...

Pass position in an array. e.g:

Integer[] asyncArray = new Integer[1];
asyncArray[0] = position;
new proveAsync().execute(asyncArray);

Answer:

You can also use constructor of AsyncTask .

class proveAsync extends AsyncTask<Void, Void, Void> {
int position;
     public proveAsync(int pos){
      position = pos;
     }

    protected void onPreExecute(){
    }

    protected Void doInBackground(Void... args) {
    }

    .
    .

then use it like:

new proveAsync(position).execute();

and you can pass anything as of requirement without changing return type and arguments in this way..