如何将对象传递给AsyncTask?

Fra*_*ero 4 java android android-asynctask

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

public Car(int idCar, String name)
{
    this.idCar = idCar;
    this.name = name;
}
Run Code Online (Sandbox Code Playgroud)

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

Car newCar = new Car(1,"StrongCar");
Run Code Online (Sandbox Code Playgroud)

我有它的问题是我想把它传递newCar给我AsyncTask,modifyCar作为参数命名,但我不知道该怎么做.

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

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

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

new modifyCar(newCar).execute();
Run Code Online (Sandbox Code Playgroud)

所以我声明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()
 {
 }
}
Run Code Online (Sandbox Code Playgroud)

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

提前致谢!

SaN*_*iaN 8

你读的解决方案是正确的,你做错了.您需要轻松地为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()
    {
    }
}
Run Code Online (Sandbox Code Playgroud)

并执行此类

// pass the object that you created
new modifyCar(newCar).execute();
Run Code Online (Sandbox Code Playgroud)