Istiyak
Istiyak

Reputation: 723

AsyncTask - How can i pass an object as parameter to an anonymous AsyncTask class

I am doing some coding stuff with android. Nearly I faced a problem and to solve this I need an anonymous AsyncTask class to execute. But I also need to pass and object to this class before execution. I tried the below code but it's not working and I did not find any solution by googling also.

 public void saveCartToRoom(CartsPay cartsPay){

    new AsyncTask<Void,Void,Void>(){

        CartsPay cartsPay;
        @Override
        protected Void doInBackground(Void... voids) {
            return null;
        }

        public void setRQ(CartsPay cartsPay){
            this.cartsPay= cartsPay;
        }

    }.setRQ(cartsPay).execute();

}

Upvotes: 1

Views: 89

Answers (2)

matdev
matdev

Reputation: 4283

Here is how to pass a CartsPay parameter to an anonymousAsyncTask

new AsyncTask<CartsPay,Void,Void>(){

        CartsPay cartsPay;

        @Override
        protected Void doInBackground(CartsPay... params) {

            this.cartsPay = params[0];

            // Your code ...

            return null;
        }

        public AsyncTask setRQ(CartsPay cartsPay){
            this.cartsPay= cartsPay;
            return this;
        }

    }.execute(cartsPay);

Upvotes: 1

Andrei T
Andrei T

Reputation: 3083

You can just do it like that:

 class CustomAsyncTask extends AsyncTask<Void, Void, Void> {
    private YourParam mParam;

    public CustomAsyncTask(YourParam param) {
       mParam = param;
    } 

    @Override
    protected doInBackground(Void.. voids){
      //do your thing.
    }
}

And then using it:

new CustomAsyncTask(param).execute();

Upvotes: 0

Related Questions