如何将对象传递给AsyncTask?

时间:2015-08-06 17:11:18

标签: java android android-asynctask

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

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

这里我没有任何问题所以我创建了一个名为Car的{​​{1}}对象,如下所示:

newCar

我遇到的问题是,我希望将此Car newCar = new Car(1,"StrongCar"); 传递给我的newCar,将AsyncTask作为参数,但我不知道如何执行此操作。< / p>

我搜索了SO,我发现了这个问题:AsyncTask passing custom objects 但它并没有解决我的问题,因为在解决方案中,它只给了modifyCar String而不是整个对象。

我希望将完整对象作为参数传递给AsyncTask。

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

AsyncTask

所以我宣布AsyncTask是这样的:

new modifyCar(newCar).execute();

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

提前致谢!

3 个答案:

答案 0 :(得分:6)

你读的解决方案是正确的,你做错了。您需要轻松地为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();

答案 1 :(得分:3)

如果您的对象是StringCarAbstractDeathRayController的实例,那么将它们传递给AsyncTask的预期方式就是通过execute方法:

new modifyCar().execute(car);

BTW,Java convention for class names将使用 CamelCase ,因此将您的班级重命名为ModifyCar可能是个好主意。

答案 2 :(得分:0)

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

  

异步任务由3种泛型类型定义,称为Params,   进度和结果,以及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);
相关问题