简体   繁体   English

AsyncTask - 如何将对象作为参数传递给匿名 AsyncTask 类

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

I am doing some coding stuff with android.我正在用android做一些编码工作。 Nearly I faced a problem and to solve this I need an anonymous AsyncTask class to execute.几乎我遇到了一个问题,为了解决这个问题,我需要一个匿名的AsyncTask类来执行。 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();

}

Here is how to pass a CartsPay parameter to an anonymous AsyncTask这是将CartsPay参数传递给匿名AsyncTask

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);

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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM