繁体   English   中英

如何将对象传递给AsyncTask?

[英]How can I pass an object to my AsyncTask?

我有一个具有此构造函数的对象Car

public Car(int idCar, String name)
{
    this.idCar = idCar;
    this.name = name;
}

在这里我没有任何问题所以我创建了一个名为newCar对象Car ,如下所示:

Car newCar = new Car(1,"StrongCar");

我有它的问题是我想将这个newCar传递给我的AsyncTask ,将modifyCar命名为参数,但我不知道如何做到这一点。

我搜索过SO,我发现了这个问题: AsyncTask传递自定义对象,但它没有解决我的问题,因为在解决方案中它给出了它们只传递一个StringAsyncTask而不是整个对象。

我想要的是将完全对象作为参数传递给AsyncTask。

根据我在上面提出的问题中给出的解决方案,我尝试将此对象传递给AsyncTask

new modifyCar(newCar).execute();

所以我声明AsyncTask是这样的:

class modifyCar extends AsyncTask<Car, Integer, ArrayList<Evento>> {
 protected void onPreExecute()
 {
 }

 protected ArrayList<Evento> doInBackground(Car... newCarAsync) 
 {
     //The rest of the code using newCarAsync
 }

 protected void onProgressUpdate()
 {
 }

 protected void onPostExecute()
 {
 }
}

但我不知道它是否正确。 如果没有,我应该为此目的做些什么?

提前致谢!

你读的解决方案是正确的,你做错了。 您需要轻松地为AsyncTask类创建构造函数并将对象传递给它

class modifyCar extends AsyncTask<Void, Integer, ArrayList<Evento>> {
    private Car newCar;

    // a constructor so that you can pass the object and use
    modifyCar(Car newCar){
        this.newCar = newCar;
    }

    protected void onPreExecute()
    {
    }

    protected ArrayList<Evento> doInBackground(Void... parms) 
    {
        //The rest of the code using newCarAsync
    }

    protected void onProgressUpdate()
    {
    }

    protected void onPostExecute()
    {
    }
}

并执行此类

// pass the object that you created
new modifyCar(newCar).execute();

如果您的对象是StringCarAbstractDeathRayController的实例,则没有区别,将它们传递给AsyncTask的预期方法是通过execute方法:

new modifyCar().execute(car);

BTW, 类名称的 Java 约定是使用CamelCase ,因此将类重命名为ModifyCar可能是个好主意。

您应该在execute方法上传递Car对象。 您可以在文档中阅读它( http://developer.android.com/reference/android/os/AsyncTask.html ):

异步任务由3种泛型类型定义,称为Params,Progress和Result,以及4个步骤,称为onPreExecute,doInBackground,onProgressUpdate和onPostExecute

请遵循文档示例:

private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
     protected Long doInBackground(URL... urls) {
         int count = urls.length;
         long totalSize = 0;
         for (int i = 0; i < count; i++) {
             totalSize += Downloader.downloadFile(urls[i]);
             publishProgress((int) ((i / (float) count) * 100));
             // Escape early if cancel() is called
             if (isCancelled()) break;
         }
         return totalSize;
     }

     protected void onProgressUpdate(Integer... progress) {
         setProgressPercent(progress[0]);
     }

     protected void onPostExecute(Long result) {
         showDialog("Downloaded " + result + " bytes");
     }
 }

并使用以下命令调用异步任务:

 new DownloadFilesTask().execute(url1, url2, url3);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM