android - 上传图片步骤中,把选中的图片存本地的方法耗时如何处理?
天蓬老师
天蓬老师 2017-04-17 15:40:17
0
2
664
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,显然这不是最好的方法,望大神们提供更加完美的解决方案。

天蓬老师
天蓬老师

欢迎选择我的课程,让我们一起见证您的进步~~

reply all(2)
巴扎黑

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.

大家讲道理

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.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!