How can I pass a primitive int to my AsyncTask?

What I want is to pass one int variable to my AsyncTask .

 int position = 5; 

And I declared my AsyncTask as follows:

 class proveAsync extends AsyncTask<int, Integer, Void> { protected void onPreExecute(){ } protected Void doInBackground(int... position) { } . . . 

But I got an error message:

A type argument cannot be a primitive type.

I can just pass the int[] and Integer variables, but never the int variable, and I execute my AsyncTask as follows:

 new proveAsync().execute(position); 

Is there anything I could do to convey just this position ?

Thanks in advance!

+6
source share
3 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(); } . . . 

at runtime do this

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

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

+14
source

Use it like that.

 class proveAsync extends AsyncTask<Integer, Void, Void> { protected void onPreExecute(){ } protected Void doInBackground(Integer... params) { int position = params[0]; ... 

Move position in array. eg:

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

You can also use the AsyncTask constructor.

 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 something as a requirement without changing the return type and arguments in this way.

+3
source

All Articles