有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何将基本int传递给AsyncTask?

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

int position = 5;

我声明我的任务如下:

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

    protected void onPreExecute(){
    }

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

    .
    .
    .

但我有一个错误,那就是:

Type argument cannot be of primitive type

我可以传递一个int[]Integer变量,但不能传递一个int变量,我执行我的AsyncTask如下:

new proveAsync().execute(position);

我能做些什么只通过这个position

提前谢谢


共 (3) 个答案

  1. # 1 楼答案

    您还可以使用AsyncTask的构造函数

    class proveAsync extends AsyncTask<Void, Void, Void> {
    int position;
         public proveAsync(int pos){
          position = pos;
         }
    
        protected void onPreExecute(){
        }
    
        protected Void doInBackground(Void... args) {
        }
    
        .
        .
    

    然后像这样使用它:

    new proveAsync(position).execute();
    

    您可以根据需要传递任何内容,而无需以这种方式更改返回类型和参数

  2. # 2 楼答案

    将参数作为Integer传递

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

    执行时,请执行此操作

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

    可以使用intValue()AsyncTask中获取int值

  3. # 3 楼答案

    像这样使用它

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

    传递数组中的位置。e、 g:

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