第十九篇 android使用ImageLoader加载本地图片

最近在项目中,需要在gridview列表或listivew列表上展示图片,但是发现图片多了出现内存溢出的情况,原因可能是使用原生的方式去获取会导致内存溢出,所以决定采用开源的ImageLoader工具类来加载本地图片.

使用开源的工具ImageLoader进行异步加载,该项目的Github地址链接:https://github.com/nostra13/Android-Universal-Image-Loader

具体使用的话,可以参考网上一些教程,使用andbase开发应该是直接集成了ImageLoader,可以直接使用,下面就主要讲一些使用过程中遇到的问题.

常见错误1:
    java.lang.IllegalStateException: ImageLoader must be init with configuration before using.

字面意思是在使用前要初始化
只要加一句话:
imageLoader.init(ImageLoaderConfiguration.createDefault(MainActivity.this));
ps: 经小伙伴们提醒,官方demo中的初始化方法是在application类中调用的


    解决方案:在Application的onCreate方法中:

        imageLoader = ImageLoader.getInstance();
    imageLoader.init(ImageLoaderConfiguration.createDefault(getApplicationContext()));


    在其他地方使用,方法如下:
        ImageLoader.getInstance().displayImage("file://" + uri, imageView);

错误2:(该错误本身还是没解决问题,请看错误3)
     java.io.FileNotFoundException: /file:/storage/emulated/0/BigNoxHD/cache/com_virtualdroid_kit_96x96.png: open failed: 
     ENOENT (No such file or directory)

    原因的uri有问题,改成如下即可:
    ImageLoader.getInstance().displayImage(String.valueOf(uri), view);


错误3: 部分图片文件夹的uri无法展示出图片.

    异常:java.io.FileNotFoundException: /storage/emulated/0/%E9%98%85%E5%9B%BE/PictureUnlock_190102.pictureunlock.jpg: 
    open failed: ENOENT (No such file or directory)。

    原因是:path路径中包含中文,中文乱码了,导致路径找不到的。


    根本原因是:ImageLoader.getInstance().displayImage()方法,接收的是一个字符串uri参数,而不是uri对象,而我直接传uri,然后
    强制转成String类型,导致该问题。

    解决办法:
        Uri uri = Uri.fromFile(file);//Uri对象
        ImageLoader.getInstance().displayImage("file://" + uri.getPath(), imageView);

问题4:图片文件夹列表 图片展示的不是前四个?点击进去也没有排序?

        1.对内容提供器排序,可以在query方法的最后一个参数加入如下:
        String sortOrder = "date_modified desc";这样才能实现降序排序,否则直接传字段是默认的升序排序.
        2.后面的则可以采用java Comparator自定义比较器实现排序.

问题5: 图片加载有些延迟,或者可能会产生溢出?

    列表上加载图片,对图片进行压缩,压缩成相应大小即可。

猜你喜欢

转载自blog.csdn.net/hhy113835/article/details/78947767
今日推荐