java - 如何避免在 AsyncTask 中传递过多的输入参数?

标签 java android object android-asynctask

我有一个 AsyncTask,我需要将多个参数传递给我的构造函数。我知道传递太多参数是不好的做法,最好将方法分成更小的 block 以避免这种情况,但我不允许破坏该方法,所以我唯一的方法是找到一种替代方法以更好的方式传递参数。在我的 AsyncTask 中,我创建了一个构造函数。

是否可以创建一个带有值对象的模型类并传递它们?我需要 getter 和 setter 吗?

 class UpdateAsyncTask extends AsyncTask<Void, Void, Void> {

        private String productId;
        int mutationAmount;
        boolean isOpeningStock;
        FlightLegIdentifier fli;
        String crew;
        String tabletId;

        UpdateAsyncTask(final String productId, final int mutationAmount, final boolean isOpeningStock,
                         final String flightKey,
                         final FlightLegIdentifier fli,
                         final String crew,
                         final String tabletId,
                         final AirFiApplication airFiApplication) {

            this.productId = productId;
            this.mutationAmount = mutationAmount;
            this.isOpeningStock = isOpeningStock;
            this.fli = fli;
            this.tabletId = tabletId;
            this.crew = crew;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            productStockAdapter.notifyDataSetChanged();
        }

        @Override
        protected Void doInBackground(Void... params) {
            StockUtils.saveMutation(productId, mutationAmount, isOpeningStock, flightKey, fli, crew,
            tabletId, getAirFiApplication());
            return null;
        }
    }

最佳答案

您可以创建一个模型类并将其作为参数传递给AsyncTask

这是一个例子:

 private static class ModelClass {
    int length;
    int height;

    ModelClass(int l, int h) {
        this.length = l;
        this.height = h;
    }
}

定义AsyncTask任务

 private class MyTask extends AsyncTask <ModelClass, Void, Void> {


    @Override
     protected void onPreExecute(){

        }

    @Override
    protected void doInBackground(ModelClass... params) {
        int length = params[0].length;
        int height = params[0].height;
        ...
        //here u can perform your saveMutation() function using the parameters...
    }

    @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
        }
}

使用Aysnctask

 //Initialize model class
ModelClass params = new ModelClass(10,10);

//pass it to asynch tash
MyTask myTask = new MyTask();
myTask.execute(params);

关于java - 如何避免在 AsyncTask 中传递过多的输入参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41356672/

相关文章:

android - 可扩展 ListView 未显示

java - 棋盘未绘制正确数量的棋子

oracle - 管理 Oracle 同义词

c++ - Qt 对象的生命周期

java - Proguard 保留所有 java 接口(interface)

java - 在 Java 中使用循环创建金字塔

java - Java 和 C++ 中双重分派(dispatch)和访问者模式的区别

java - 如何在另一个 Activity 的 if-else 语句中使用来自单独 Activity 的 boolean 变量

java - 提交的 EditText 不会相应地表现

Java - javax.net.ssl.SSLPeerUnverifiedException : peer not authenticated