for (int i=0;i<paths.size();i++) {
Bitmap bitmap = ImageCompressUtil.compressBySize(paths.get(i), 1000, 1000);
ImageTools.savePhotoToSDCard(bitmap, Constants.MyAvatarDir, i + "");
newPaths.add(Constants.MyAvatarDir + i + ".jpg");
}
代码如上,paths为一个选中图片地址的list,现在我遍历他,进行压缩,以1、2、3数字来命名,并存入本地,在将压缩后的地址存入newpaths中,传入adapter显示。
现在出现了个问题,选中的图片还没来得及存入本地,覆盖原本以1、2、3数字来命名的图片,就传入adapter中,所以显示的图片是上次存的图片。
我的解决方法是延迟500ms后才传入adapter,显然这不是最好的方法,望大神们提供更加完美的解决方案。
巴扎黑2017-04-17 15:42:17
It depends on where you setAdapter and notifyDataSetChanged. If it is in a different thread than the above code block, your situation may occur. The above code block should be executed before calling the adapter refresh method. This is Be sure.
大家讲道理2017-04-17 15:42:17
You can use the observer pattern and pass a Listener to your ImageTools.savePhotoToSDCard
method,
Interface OnSavePhotoToSDCardListener {
void onSaveSucceed();
void onSaveFailed();
}
So the code should be changed to this
for (int i=0;i<paths.size();i++) {
final int token = i;
Bitmap bitmap = ImageCompressUtil.compressBySize(paths.get(i), 1000, 1000);
ImageTools.savePhotoToSDCard(bitmap, Constants.MyAvatarDir, token + "", new OnSavePhotoToSDCardListener() {
@Override
public void onSaveSucceed() {
newPaths.add(Constants.MyAvatarDir + token + ".jpg");
}
@Override
public void onSaveSucceed() {
//do something
}
});
}
Of course, it is recommended that you correctly handle the timing of setAdapter
and adapter.notifyDataSetChanged()
calls.