Skip to content Skip to sidebar Skip to footer

Android Image Caching For Bitmaps

HI i was implementing image Caching in Android. Have gone thorough this http://developer.android.com/training/displaying-bitmaps/cache-bitmap.html public class ImageCache extends

Solution 1:

This is what you Exactly WAnt i have been doing so in my Projects Using These Classes Just Simply Copy and Paste them in Your Project

ImageLoader.java

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Collections;
import java.util.Map;
import java.util.WeakHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.widget.ImageView;

publicclassImageLoader {

    MemoryCache memoryCache=newMemoryCache();
    FileCache fileCache;
    private Map<ImageView, String> imageViews=Collections.synchronizedMap(newWeakHashMap<ImageView, String>());
    ExecutorService executorService; 

    publicImageLoader(Context context){
        fileCache=newFileCache(context);
        executorService=Executors.newFixedThreadPool(5);
    }

    intstub_id= R.drawable.ic_launcher;
    publicvoidDisplayImage(String url, int loader, ImageView imageView)
    {
        stub_id = loader;
        imageViews.put(imageView, url);
        Bitmap bitmap=memoryCache.get(url);
        if(bitmap!=null)
            imageView.setImageBitmap(bitmap);
        else
        {
            queuePhoto(url, imageView);
            imageView.setImageResource(loader);
        }
    }

    privatevoidqueuePhoto(String url, ImageView imageView)
    {
        PhotoToLoad p=newPhotoToLoad(url, imageView);
        executorService.submit(newPhotosLoader(p));
    }

    private Bitmap getBitmap(String url)
    {
        File f=fileCache.getFile(url);

        //from SD cacheBitmapb= decodeFile(f);
        if(b!=null)
            return b;

        //from webtry {
            Bitmap bitmap=null;
            URLimageUrl=newURL(url);
            HttpURLConnectionconn= (HttpURLConnection)imageUrl.openConnection();
            conn.setConnectTimeout(30000);
            conn.setReadTimeout(30000);
            conn.setInstanceFollowRedirects(true);
            InputStream is=conn.getInputStream();
            OutputStreamos=newFileOutputStream(f);
            Utils.CopyStream(is, os);
            os.close();
            bitmap = decodeFile(f);
            return bitmap;
        } catch (Exception ex){
           ex.printStackTrace();
           returnnull;
        }
    }

    //decodes image and scales it to reduce memory consumptionprivate Bitmap decodeFile(File f){
        try {
            //decode image size
            BitmapFactory.Optionso=newBitmapFactory.Options();
            o.inJustDecodeBounds = true;
            BitmapFactory.decodeStream(newFileInputStream(f),null,o);

            //Find the correct scale value. It should be the power of 2.finalint REQUIRED_SIZE=70;
            int width_tmp=o.outWidth, height_tmp=o.outHeight;
            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.Optionso2=newBitmapFactory.Options();
            o2.inSampleSize=scale;
            return BitmapFactory.decodeStream(newFileInputStream(f), null, o2);
        } catch (FileNotFoundException e) {}
        returnnull;
    }

    //Task for the queueprivateclassPhotoToLoad
    {
        public String url;
        public ImageView imageView;
        publicPhotoToLoad(String u, ImageView i){
            url=u;
            imageView=i;
        }
    }

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

        @Overridepublicvoidrun() {
            if(imageViewReused(photoToLoad))
                return;
            Bitmap bmp=getBitmap(photoToLoad.url);
            memoryCache.put(photoToLoad.url, bmp);
            if(imageViewReused(photoToLoad))
                return;
            BitmapDisplayer bd=newBitmapDisplayer(bmp, photoToLoad);
            Activity a=(Activity)photoToLoad.imageView.getContext();
            a.runOnUiThread(bd);
        }
    }

    booleanimageViewReused(PhotoToLoad photoToLoad){
        String tag=imageViews.get(photoToLoad.imageView);
        if(tag==null || !tag.equals(photoToLoad.url))
            returntrue;
        returnfalse;
    }

    //Used to display bitmap in the UI threadclassBitmapDisplayerimplementsRunnable
    {
        Bitmap bitmap;
        PhotoToLoad photoToLoad;
        publicBitmapDisplayer(Bitmap b, PhotoToLoad p){bitmap=b;photoToLoad=p;}
        publicvoidrun()
        {
            if(imageViewReused(photoToLoad))
                return;
            if(bitmap!=null)
                photoToLoad.imageView.setImageBitmap(bitmap);
            else
                photoToLoad.imageView.setImageResource(stub_id);
        }
    }

    publicvoidclearCache() {
        memoryCache.clear();
        fileCache.clear();
    }

}

FileCache.java

FileCache.java

import java.io.File;
import android.content.Context;

publicclassFileCache {

    privateFile cacheDir;

    publicFileCache(Context context){
        //Find the dir to save cached imagesif (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))
            cacheDir=newFile(android.os.Environment.getExternalStorageDirectory(),"TempImages");
        else
            cacheDir=context.getCacheDir();
        if(!cacheDir.exists())
            cacheDir.mkdirs();
    }

    publicFilegetFile(String url){
        String filename=String.valueOf(url.hashCode());
        File f = newFile(cacheDir, filename);
        return f;

    }

    publicvoidclear(){
        File[] files=cacheDir.listFiles();
        if(files==null)
            return;
        for(Filef:files)
            f.delete();
    }

}

MemoryCache.java

import java.lang.ref.SoftReference;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import android.graphics.Bitmap;

publicclassMemoryCache {
    private Map<String, SoftReference<Bitmap>> cache=Collections.synchronizedMap(newHashMap<String, SoftReference<Bitmap>>());

    public Bitmap get(String id){
        if(!cache.containsKey(id))
            returnnull;
        SoftReference<Bitmap> ref=cache.get(id);
        return ref.get();
    }

    publicvoidput(String id, Bitmap bitmap){
        cache.put(id, newSoftReference<Bitmap>(bitmap));
    }

    publicvoidclear() {
        cache.clear();
    }
}

Utils.java

import java.io.InputStream;
import java.io.OutputStream;

publicclassUtils {
    publicstaticvoidCopyStream(InputStream is, OutputStream os)
    {
        finalint buffer_size=1024;
        try
        {
            byte[] bytes=newbyte[buffer_size];
            for(;;)
            {
              int count=is.read(bytes, 0, buffer_size);
              if(count==-1)
                  break;
              os.write(bytes, 0, count);
            }
        }
        catch(Exception ex){}
    }
}

to use These all you need to do is just

publicclassAndroidLoadImageFromURLActivityextendsActivity {
    @OverridepublicvoidonCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        // Loader image - will be shown before loading imageintloader= R.drawable.loader;

        // Imageview to showImageViewimage= (ImageView) findViewById(R.id.image);

        // Image urlStringimage_url="TOUR IMAGE URL";

        // ImageLoader class instanceImageLoaderimgLoader=newImageLoader(getApplicationContext());

        // whenever you want to load an image from url// call DisplayImage function// url - image url to load// loader - loader image, will be displayed before getting image// image - ImageView 
        imgLoader.DisplayImage(image_url, loader, image);
    }
}

Criteria Whenever there is a URL mismatch images are gonna be loaded from server and when you have them stored locally they will never be downloaded from server rather shown from cache

Post a Comment for "Android Image Caching For Bitmaps"