我有一个对象 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 passing custom objects
但它并没有解决我的问题,因为在给出的解决方案中,他们只将 String
传递给 AsyncTask
而不是整个对象。
我想要的是将整个对象作为参数传递给 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();
关于java - 如何将对象传递给我的 AsyncTask?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31861848/