【问题标题】:storing images into sd card after loading it in listview在列表视图中加载图像后将图像存储到 sd 卡中
【发布时间】:2012-08-20 13:13:55
【问题描述】:

我正在将图像从服务器下载到 ListView ,现在要执行此任务,我正在使用 ImageDownloader 示例代码。到目前为止它工作正常。

但我想将ListViewsave 图像放在SD card 中,但我很困惑何时存储图像,因为图像正在异步下载,并且由于 ViewHolder 模式对我来说很难判断。

一旦我将它存储在 SD 卡中,下次我只想从内存中读取它。

ImageDownload 将位图存储在缓存中,并在下载后从那里获取它。但问题是它的行为是不可预测的。

有时它从服务器下载,有时从缓存中下载。

所以任何人都可以帮助我找到将图像存储在 sd 卡中一次的正确位置。

【问题讨论】:

    标签: android android-listview android-imageview


    【解决方案1】:

    修改您的 ImageDownloader 类以像这样保存图像:

    • 为下载方法添加一个参数,如:
     download(String url, ImageView imageView, Boolean saveData)
    
    • 在你的 ID 类中创建一个全局变量 saveData:

    私有布尔保存数据;

    并将下载d方法中作为参数给出的值存储在其中:

    this.saveData = saveData;

    • BitmapDownloaderTask 的 onPostExecute 方法应如下所示:

    @覆盖 受保护的无效onPostExecute(位图位图){ if (isCancelled()) { 位图=空; }

            addBitmapToCache(url, bitmap);
    
            if (saveData == true) {
                try {
                    FileOutputStream out = new FileOutputStream(path);
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
    
            if (imageViewReference != null) {
                ImageView imageView = imageViewReference.get();
                BitmapDownloaderTask bitmapDownloaderTask = getBitmapDownloaderTask(imageView);
                // Change bitmap only if this process is still associated with it
                if (this == bitmapDownloaderTask) {
                    imageView.setImageBitmap(bitmap);
                }
            }
        }
    

    其中 path 是您要保存图像的路径。

    下次您要加载图像之前,您必须查看它是否已经下载并从路径加载,否则调用 ImageDownloader。

    就是这样!享受吧!

    【讨论】:

    • 嗯,我想检查所有图像何时下载。因为只要在 getView() 中加载列表项,就会执行 'download(String url, ImageView imageView, Boolean saveData)` 函数
    猜你喜欢
    • 1970-01-01
    • 2011-12-12
    • 1970-01-01
    • 1970-01-01
    • 2011-07-19
    • 1970-01-01
    • 2019-09-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多