在堆栈溢出时阅读这里的几个问题,但找不到工作解决方案。
我的场景=>在onActivityResult方法中,接收一个列表,该列表将发送到Async Task以进行某些后台工作。执行一些工作后,它会发回一个列表说输出。在Async回调中接收输出后,记录输出列表并按预期工作。
现在从这里,我想把它放在一个Arraylist说addProductModelListTemp所以我可以添加更多的对象。但是,如上所述,在后台添加其他对象时,addProductModelListTemp将覆盖所有索引,并在Async回调中接收最后一个输出列表。下面是我如何更新addProductModelListTemp的代码。 currentRowIdToInsertImages是在addProductModelListTemp中插入对象的索引,它工作正常(为简单起见,此处不包括)
new CompressFileAsyncTask(new AsyncResponse() {
@Override
public void processFinish(List<Uri> output) {
for (int i = 0; i < output.size(); i++) {
Timber.e("Received from Async Class contains => " + output.get(i));
}
AddProductModel tempProductModel = new AddProductModel("", "", "", dummyList);// Dummy list is an empty list you can assume ... Tried setting it directly as well with the **output**
addProductModelListTemp.add(tempProductModel);
addProductModelListTemp.get(currentRowIdToInsertImages).setImagePathList(output);
for (int i = 0; i < addProductModelListTemp.size(); i++) {
Timber.e("addProductModelListTemp index " + i);
for (int k = 0; k < addProductModelListTemp.get(i).getImagePathList().size(); k++) {
Timber.e("addProductModelListTemp.get(i).getImagePathList() index " + k + " contains " + addProductModelListTemp.get(i).getImagePathList().get(k));
}
}
}
}).execute(imageURIList); // imageURIList is the list received in onActivityResult method
下面是我正在创建和更新对象的模型类。
public AddProductModel(String size, String color, String quantity, List<Uri> imagePath) {
this.size = size;
this.color = color;
this.quantity = quantity;
this.imagePath = imagePath;
}
public void setImagePathList(List<Uri> imagePath) {
if (this.imagePath.isEmpty()) {
Timber.e("Image Path List not exists, adding");
this.imagePath = imagePath;
} else {
Timber.e("Image Path List exists, appending");
this.imagePath.addAll(this.imagePath.size(), imagePath);
}
} // Getter setter not attached for clarity}
AsyncTask类是
class CompressFileAsyncTask extends AsyncTask<List<Uri>, Void, List<Uri>> {
public AsyncResponse asyncResponse = null;
public CompressFileAsyncTask(AsyncResponse asyncResponse) {
this.asyncResponse = asyncResponse;
}
@Override
protected List<Uri> doInBackground(List<Uri>... imageUriList) {
List<Uri> fileList = imageUriList[0];
for (int i = 0; i < fileList.size(); i++) {
filesAdded.add(Uri.parse(compressImage(String.valueOf(fileList.get(i)))));
}
return filesAdded;
}
@Override
protected void onPostExecute(List<Uri> uriArrayList) {
asyncResponse.processFinish(uriArrayList);
}
}
和界面本身
public interface AsyncResponse {
public void processFinish(List<Uri> output);
}
问题是您正在修改相同的列表对象并将其存储在addProductModelListTemp
的每个索引中。你需要使filesAdded
成为局部变量。
@Override
protected List<Uri> doInBackground(List<Uri>... imageUriList) {
List<Uri> fileList = imageUriList[0];
List<Uri> filesAdded = new ArrayList<>();
for (int i = 0; i < fileList.size(); i++) {
filesAdded.add(Uri.parse(compressImage(String.valueOf(fileList.get(i)))));
}
return filesAdded;
}