Java 延迟加载带有进度条的图像会使图像在显示时损坏

Java 延迟加载带有进度条的图像会使图像在显示时损坏,java,android,Java,Android,我有一个应用程序显示来自服务器的图像。现在我懒洋洋地加载我的图像。 因此,最初,当图像加载完成时,我会显示一个进度条。我将进度条设置为visibility属性为View.INVISIBLE,然后图像就会显示出来。这是我用于图像的布局文件 <?xml version="1.0" encoding="utf-8"?> <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" android

我有一个应用程序显示来自服务器的图像。现在我懒洋洋地加载我的图像。 因此,最初,当图像加载完成时,我会显示一个进度条。我将进度条设置为
visibility
属性为
View.INVISIBLE
,然后图像就会显示出来。这是我用于图像的布局文件

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_gravity="center" >

     <ImageView
            android:id="@+id/imageView1"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_gravity="center"
            android:contentDescription="@string/app_name"
            android:scaleType="centerInside"
            android:src="@drawable/ic_launcher" />

    <RelativeLayout
        android:id="@+id/loading_layout"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:background="@android:color/white" >

        <ProgressBar
            android:id="@+id/progressBar1"
            style="?android:attr/progressBarStyleSmall"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:layout_centerVertical="true"
            android:background="@android:color/white" />
    </RelativeLayout>

</FrameLayout>

问题 当进度条消失时,屏幕上显示的图像已损坏。喜欢这个图像吗

当我刷新从缓存目录加载的图像列表时,当它们显示在屏幕上时,它们正确显示,没有任何损坏

ImageLoader类我用来延迟加载图像

public class ImageLoader {
    // @@ JUST FOR THIS PROJECT
    BaseAdapter mAdapter;
    // @@
    MemoryCache memoryCache = new MemoryCache();
    FileCache fileCache;
    private Map<ImageView, String> imageViews = Collections
            .synchronizedMap(new WeakHashMap<ImageView, String>());
    ExecutorService executorService;

    boolean addRoundCournerAndStroke = false;
    boolean scale = false;

    boolean localfile = false;
    int default_image;

    public ImageLoader(Context context, boolean flag, boolean scale,
            boolean localfile) {
        fileCache = new FileCache(context);
        this.addRoundCournerAndStroke = flag;
        executorService = Executors.newFixedThreadPool(5);
        this.scale = scale;
        this.localfile = localfile;

    }

    public ImageLoader(Context context, boolean flag, boolean scale,
            boolean localfile, int default_image_id) {
        this(context, flag, scale, localfile);
        this.default_image = default_image_id;
    }

    public ImageLoader(Context context, boolean flag, boolean scale,
            boolean localfile, int default_image_id, BaseAdapter adapter) {
        this(context, flag, scale, localfile);
        this.default_image = default_image_id;
        this.mAdapter = adapter;
    }

    public void DisplayImage(String url, ImageView imageView) {
        imageViews.put(imageView, url);
        Bitmap bitmap = memoryCache.get(url);
        if (bitmap != null) {
            changeProgressBarVisibilty(imageView, false);
            imageView.setImageBitmap(bitmap);
        }

        else {
            queuePhoto(url, imageView);
            imageView.setImageResource(this.default_image);
        }
    }

    private void queuePhoto(String url, ImageView imageView) {
        PhotoToLoad p = new PhotoToLoad(url, imageView);
        executorService.submit(new PhotosLoader(p));
    }

    private Bitmap getBitmap(String url) {
        File f = null;
        if (localfile)
            f = new File(url);
        else
            f = fileCache.getFile(url);

        // Log.d("bytes", "decode");
        // from SD cache
        Bitmap b = decodeFile(f);
        if (b != null)
            return b;

        // from web
        try {
            Bitmap bitmap = null;

            URL imageUrl = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) imageUrl
                    .openConnection();
            conn.setConnectTimeout(30000);
            conn.setReadTimeout(30000);
            conn.setInstanceFollowRedirects(true);
            InputStream is = conn.getInputStream();
            OutputStream os = new FileOutputStream(f);
            Utils.CopyStream(is, os);
            os.close();

            bitmap = decodeFile(f);
            // //Log.d("bytes", "decode");
            return bitmap;
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }
    }

    private Bitmap decodeFileWithoutScaling(File f) {
        try {
            BitmapFactory.Options o2 = new BitmapFactory.Options();
            o2.inSampleSize = 1;
            //o2.inPurgeable = true;
            if (this.localfile)
                return BitmapFactory.decodeFile(f.getAbsolutePath(), o2);
            else
                return BitmapFactory.decodeStream(new FileInputStream(f), null,
                        o2);
        } catch (FileNotFoundException e) {
        }
        return null;
    }

    private Bitmap decodeFile(File f) {

        if (this.scale) {
            return decodeFileWithScalling(f);
        } else {
            return decodeFileWithoutScaling(f);
        }
    }

    // decodes image and scales it to reduce memory consumption
    private Bitmap decodeFileWithScalling(File f) {
        try {
            // decode image size
            BitmapFactory.Options o = new BitmapFactory.Options();
            o.inJustDecodeBounds = true;

        //  o.inPurgeable = true;
            if (this.localfile)
                BitmapFactory.decodeFile(f.getAbsolutePath(), o);
            else
                BitmapFactory.decodeStream(new FileInputStream(f), null, o);

            // Find the correct scale value. It should be the power of 2.
            final int REQUIRED_SIZE = 70;
            int width_tmp = o.outWidth, height_tmp = o.outHeight;
            // Log.d("width", width_tmp + "");
            // Log.d("height", height_tmp + "");
            int scale = 1;
            while (true) {
                if (width_tmp / 2 < REQUIRED_SIZE
                        || height_tmp / 2 < REQUIRED_SIZE)
                    break;
                width_tmp /= 2;
                height_tmp /= 2;
                scale *= 2;
            }

            // decode with inSampleSize
            BitmapFactory.Options o2 = new BitmapFactory.Options();
            o2.inSampleSize = scale;
        //  o2.inPurgeable = true;
            // Log.d("after shave width", o2.outWidth + "");
            // Log.d("after shave height", o2.outHeight + "");
            if (this.localfile)
                return BitmapFactory.decodeFile(f.getAbsolutePath(), o2);
            else
                return BitmapFactory.decodeStream(new FileInputStream(f), null,
                        o2);
        } catch (FileNotFoundException e) {
        }
        return null;
    }

    // Task for the queue
    private class PhotoToLoad {
        public String url;
        public ImageView imageView;

        public PhotoToLoad(String u, ImageView i) {
            url = u;
            imageView = i;
        }
    }

    class PhotosLoader implements Runnable {
        PhotoToLoad photoToLoad;

        PhotosLoader(PhotoToLoad photoToLoad) {
            this.photoToLoad = photoToLoad;
        }

        public void run() {
            if (imageViewReused(photoToLoad)) {
                return;
            }

            Bitmap bmp = getBitmap(photoToLoad.url);

            // if (addRoundCournerAndStroke) {
            // // bmp = ImageHelper.rotateAndFrame(bmp, 10);
            // bmp = ImageHelper.getRoundedCornerBitmap(bmp, 10);
            // }

            memoryCache.put(photoToLoad.url, bmp);
            if (imageViewReused(photoToLoad))
                return;
            BitmapDisplayer bd = new BitmapDisplayer(bmp, photoToLoad);
            Activity a = (Activity) photoToLoad.imageView.getContext();
            a.runOnUiThread(bd);
        }
    }

    boolean imageViewReused(PhotoToLoad photoToLoad) {
        String tag = imageViews.get(photoToLoad.imageView);
        if (tag == null || !tag.equals(photoToLoad.url))
            return true;
        return false;
    }

    // Used to display bitmap in the UI thread
    class BitmapDisplayer implements Runnable {
        Bitmap bitmap;
        PhotoToLoad photoToLoad;

        public BitmapDisplayer(Bitmap b, PhotoToLoad p) {
            bitmap = b;
            photoToLoad = p;
        }

        public void run() {
            if (imageViewReused(photoToLoad))
                return;
            changeProgressBarVisibilty(photoToLoad.imageView, false);
            if (bitmap != null) {
                photoToLoad.imageView.setImageBitmap(bitmap);


            } else {
                photoToLoad.imageView
                        .setImageResource(ImageLoader.this.default_image);

            }
            if (mAdapter != null) {
                mAdapter.notifyDataSetChanged();
            }

        }
    }

    private void changeProgressBarVisibilty(ImageView image, boolean visible) {
        ViewGroup layout = (ViewGroup) image.getParent();

        try {
            View v = layout.findViewById(R.id.loading_layout);
            v.setVisibility(visible ? View.VISIBLE : View.GONE);
        } catch (Exception ex) {
            ex.printStackTrace();
        }



    }



    public void clearCache() {
        memoryCache.clear();
        fileCache.clear();
    }

}
公共类ImageLoader{
//只是为了这个项目
基本适配器mAdapter;
// @@
MemoryCache MemoryCache=新的MemoryCache();
文件缓存文件缓存;
私有地图图像视图=集合
.synchronizedMap(新WeakHashMap());
执行服务执行服务;
布尔addRoundCournedStroke=false;
布尔标度=假;
布尔localfile=false;
int默认_图像;
公共图像加载器(上下文上下文、布尔标志、布尔比例、,
布尔值(本地文件){
fileCache=新的fileCache(上下文);
this.addRoundCournedStroke=标志;
executorService=Executors.newFixedThreadPool(5);
这个比例=比例;
this.localfile=localfile;
}
公共图像加载器(上下文上下文、布尔标志、布尔比例、,
布尔本地文件,int默认值(图像id){
这(上下文、标志、比例、本地文件);
this.default\u image=default\u image\u id;
}
公共图像加载器(上下文上下文、布尔标志、布尔比例、,
布尔本地文件,int默认值\u图像\u id,BaseAdapter){
这(上下文、标志、比例、本地文件);
this.default\u image=default\u image\u id;
this.mAdapter=适配器;
}
public void DisplayImage(字符串url,ImageView){
put(imageView,url);
位图位图=memoryCache.get(url);
if(位图!=null){
ChangeProgressBarVisibility(imageView,false);
设置图像位图(位图);
}
否则{
队列照片(url、imageView);
setImageResource(此.default_图像);
}
}
私有void队列照片(字符串url,ImageView){
PhotoToLoad p=新的PhotoToLoad(url,imageView);
executorService.submit(新的PhotoLoader(p));
}
私有位图getBitmap(字符串url){
文件f=null;
如果(本地文件)
f=新文件(url);
其他的
f=fileCache.getFile(url);
//Log.d(“字节”,“解码”);
//从SD缓存
位图b=解码文件(f);
如果(b!=null)
返回b;
//从网络
试一试{
位图=空;
URL imageUrl=新URL(URL);
HttpURLConnection conn=(HttpURLConnection)imageUrl
.openConnection();
连接设置连接超时(30000);
连接设置读取超时(30000);
conn.setInstanceFollowRedirects(真);
InputStream is=conn.getInputStream();
OutputStream os=新文件OutputStream(f);
Utils.CopyStream(is,os);
os.close();
位图=解码文件(f);
////Log.d(“字节”,“解码”);
返回位图;
}捕获(例外情况除外){
例如printStackTrace();
返回null;
}
}
无缩放的专用位图解码文件(文件f){
试一试{
BitmapFactory.Options o2=新的BitmapFactory.Options();
o2.inSampleSize=1;
//o2.InPurgable=真;
if(此.localfile)
返回BitmapFactory.decodeFile(f.getAbsolutePath(),o2);
其他的
返回BitmapFactory.decodeStream(新文件输入流(f),null,
氧气);
}catch(filenotfounde异常){
}
返回null;
}
私有位图解码文件(文件f){
如果(这个比例){
返回呼叫(f);
}否则{
返回不带缩放的解码文件(f);
}
}
//对图像进行解码和缩放以减少内存消耗
专用位图解码文件(文件f){
试一试{
//解码图像大小
BitmapFactory.Options o=新的BitmapFactory.Options();
o、 inJustDecodeBounds=true;
//o.inpurgable=true;
if(此.localfile)
解码文件(f.getAbsolutePath(),o);
其他的
解码流(新的FileInputStream(f),null,o);
//找到正确的刻度值。它应该是2的幂。
所需的最终int_尺寸=70;
内部宽度=o.向外宽度,高度=o.向外高度;
//Log.d(“宽度”,宽度_tmp+”);
//Log.d(“高度”,高度+tmp+”);
int标度=1;
while(true){
如果(宽度\u tmp/2<要求的\u尺寸
||高度(tmp/2<所需尺寸)
打破
宽度_tmp/=2;
高度_tmp/=2;
比例*=2;
}
//用inSampleSize解码
BitmapFactory.Options o2=新的BitmapFactory.Options();
o2.inSampleSize=刻度;
//o2.InPurgable=真;
//对数d(“剃须宽度后”,o2.外径+”);
//Log.d(“剃须高度后”,o2.outHeight+);
if(此.localfile)
返回BitmapFactory.decodeFile(f.getAbsolutePath(),o2);
其他的
返回BitmapFactory.decodeStream(新文件输入流(f),null,