【问题标题】:How can I pass a primitive int to my AsyncTask?如何将原始 int 传递给我的 AsyncTask?
【发布时间】:2015-11-11 04:58:04
【问题描述】:

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

int position = 5;

我这样声明了我的 AsyncTask:

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

    protected void onPreExecute(){
    }

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

    .
    .
    .

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

类型参数不能是原始类型

我只能传递 int[]Integer 变量,但绝不传递 int 变量,我会像这样执行 AsyncTask

new proveAsync().execute(position);

我可以做些什么来只传递这个position

提前致谢!

【问题讨论】:

    标签: java android android-asynctask


    【解决方案1】:

    将您的参数传递为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值

    【讨论】:

    • 为什么必须像数组一样引用位置? position[0]
    • 因为... 意味着它可以接受任意数量的参数并且它们像数组一样被传递。如果您只传递一个参数,则获取第一个值。
    • 因为...表示它是一个数组。这意味着调用函数(在这种情况下,过滤到 execute(...))可以有一个或多个整数。你可以有.execute(1);.execute(1, 2, 3).execute(intArray)
    • 感谢您的解释!你帮了我很多;)
    • 我可能应该提到一个或多个是错误的。在我的解释中。您也可以不输入.execute();。在这种情况下,上面示例中的代码会因IndexOutOfBoundsException 而崩溃。您可以通过一些简单的逻辑检查来防止这种情况发生,尽管作为 doInBackground 的第一行
    【解决方案2】:

    像这样使用它。

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

    在数组中传递位置。例如:

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

    【讨论】:

    • 感谢您帮助以不同的视角展示此过程。
    【解决方案3】:

    你也可以使用 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();
    

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

    【讨论】:

    • 什么效率更高?用构造函数传递还是作为参数传递?
    • 像这样完成时会绕过 AsyncTask 的预期功能。尽管代码的功能是按您希望的方式执行的,但它看起来很脏。至少在我看来。
    • 感谢@Knossos 的解释!
    • 如果你想传递一个上下文怎么办。
    • 我在第一行提到“你也可以使用 AsyncTask 的构造函数”我没有说这是唯一的方法。
    猜你喜欢
    • 2013-07-13
    • 2012-08-17
    • 1970-01-01
    • 1970-01-01
    • 2017-09-20
    • 2011-02-27
    • 2015-06-16
    • 1970-01-01
    相关资源
    最近更新 更多