使用自定义ListView适配器的位图

时间:2014-04-11 22:27:20

标签: android android-listview bitmap android-adapter

我正在尝试从自定义适配器将图像加载到我的列表视图中,但是在我向下滚动然后向上滚动并且我不知道原因之前,位图不会显示图像!首先,当我加载图像时,应用程序崩溃,因为我没有有效地加载图像。

(我通过编码到base64将数据存储在数据库中。我知道这不是一件好事,但我需要尽快完成工作。)

奖金问题在两个异步数据库调用完成后触发事件的最佳方法是什么?

加载位图的代码:

public Bitmap decodeBitmap(String image, int reqWidth, int reqHeight)
    {
        byte[] decodedByte = Base64.decode(image, 0);
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeByteArray(decodedByte, 0, decodedByte.length, options);

        options.inSampleSize = calculateSize(options, reqWidth, reqHeight);

        // Decode bitmap with inSampleSize set
        options.inJustDecodeBounds = false;
        Bitmap bmp = BitmapFactory.decodeByteArray(decodedByte, 0, decodedByte.length, options);
        return bmp;
    }

    public int calculateSize(BitmapFactory.Options options, int reqWidth, int reqHeight)
    {

        final int height = options.outHeight;
        final int width = options.outWidth;
        int size = 1;

        if (height > reqHeight || width > reqWidth)
        {
            if (width > height)
            {
                size = Math.round((float) height / (float) reqHeight);
            }
            else
            {
                size = Math.round((float) width / (float) reqWidth);
            }
        }
        return size;
    }

ListView

1 个答案:

答案 0 :(得分:1)

将图像加载到imageview中的最佳和最简单的方法是使用后台进程来完成任务,因为阻止界面将是糟糕的用户体验。网上有很多代码示例,例如你可以使用this教程中的ImageLoader类。只需将其添加到您的项目中即可使用它:

ImageLoader loader = new ImageLoader(context);
loader.DisplayImage(url, imagview);

修改 当您从Web上获取它时,您很可能将图像作为流获取。您可以这样做,但处理数据库中图像的最有效和最流行的方法是不将实际图像数据存储在数据库中,因为读/写操作效率不高。

相反,您可以做的是将从Web获取的流存储到某个文件夹中的文件,然后在存储它之后,将指向它的路径存储在图像所在的数据库中。通过这种方式,您的数据库更轻,并且只在您需要时打开图像。实际上这是处理图像的正确方法,因为一旦图像大小增加,就无法从中读取,因为Android将光标窗口大小限制为1MB。

因此,我建议您按照说明修改代码。