如何将原始int传递给我的AsyncTask?

Fra*_*ero 8 java android android-asynctask

我想要的是将一个int变量传递给我AsyncTask.

int position = 5;
Run Code Online (Sandbox Code Playgroud)

我宣布我的AsyncTask是这样的:

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

    protected void onPreExecute(){
    }

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

    .
    .
    .
Run Code Online (Sandbox Code Playgroud)

但我得到一个错误,它是以下内容:

类型参数不能是基本类型

我只能传递一个int[]和Integer变量,但从来没有int变量,我AsyncTask像这样执行:

new proveAsync().execute(position);
Run Code Online (Sandbox Code Playgroud)

我能做些什么来传递这个position吗?

提前致谢!

Roh*_*5k2 17

将参数传递为 Integer

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

    protected void onPreExecute(){
    }

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

    .
    .
    .
Run Code Online (Sandbox Code Playgroud)

执行时执行此操作

new proveAsync().execute(new Integer(position));
Run Code Online (Sandbox Code Playgroud)

你可以得到int值AsyncTask作为使用intValue()

  • 因为`...`意味着它可以接受任意数量的参数,并且它们像数组一样传递.如果只传递一个参数,则获取第一个值. (3认同)
  • 因为```表示它是一个数组.这意味着调用函数(在这种情况下,向下过滤到执行(...))可以给它一个或多个整数.你可以有`.execute(1);`或`.execute(1,2,3)`或`.execute(intArray)` (3认同)
  • 为什么要像数组一样引用位置?`position [0]` (2认同)

Ade*_*mad 5

像这样使用它.

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

    protected void onPreExecute(){
    }

    protected Void doInBackground(Integer... params) {
        int position = params[0];
    ...
Run Code Online (Sandbox Code Playgroud)

传递阵列中的位置.例如:

Integer[] asyncArray = new Integer[1];
asyncArray[0] = position;
new proveAsync().execute(asyncArray);
Run Code Online (Sandbox Code Playgroud)