我有一个 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/