Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I pass an object to my AsyncTask?

I have an object Car that has this constructor:

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

Here I don't have any problem so I created one object Car named newCar, like this:

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

The problem that I have it's that I want to pass this newCar to my AsyncTask, named modifyCar as a parameter, but I don't know how to do this.

I have searched in SO and I found this question: AsyncTask passing custom objects but it doesn't solved my problem because in the solution that it is given they only pass an String to the AsyncTask and not the entirely object.

What I want it's to pass the entirely object as a parameter to the AsyncTask.

According to the solution that it is given in the question that I put above, I tried to do this to pass the object to the AsyncTask.

new modifyCar(newCar).execute();

So I declared the AsyncTask like this:

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()
 {
 }
}

But I don't know if it is correct or not. If not, what I should do for that purpose?

Thanks in advance!

like image 487
Francisco Romero Avatar asked Dec 15 '22 12:12

Francisco Romero


2 Answers

The solution that you read is right, you just did it wrong. You needed to create a constructor for your AsyncTask class easily and pass the object to it

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()
    {
    }
}

and to execute this class

// pass the object that you created
new modifyCar(newCar).execute();
like image 51
SaNtoRiaN Avatar answered Dec 21 '22 09:12

SaNtoRiaN


It makes no difference if your object is an instance of String or a Car or a AbstractDeathRayController, the expected way to pass them to an AsyncTask is through the execute method:

new modifyCar().execute(car);

BTW, Java convention for class names is to use CamelCase, so it might be a good idea to rename your class to ModifyCar.

like image 20
Sebastian Avatar answered Dec 21 '22 09:12

Sebastian