Skip to main content

Faster Loading images in GridViews or ListViews in Android using Menory Caching, Complete implemenation with sample code.

This example shows you how to load large images in the gridview without any lag or without outofmemory error.
This sample application uses the LruCache to hold the images.
A cache that holds strong references to a limited number of values. Each time a value is accessed, it is moved to the head of a queue. When a value is added to a full cache, the value at the end of that queue is evicted and may become eligible for garbage collection.

Read more from here.

This is the MainActivity that holds the GridView. We are adding here 100 images in the Grid to load. This time I am loading images from the resources.
import java.util.ArrayList;
import android.os.Bundle;
import android.widget.GridView;
public class MainActivity extends Activity {
    protected void onCreate(Bundle savedInstanceState) {
        ArrayList<string> items = new ArrayList<string>();
        // adding 100 images
        for (int p = 0; p < 100; p++) {
        ListAdapter list = new ListAdapter(this, items);
        GridView grid = new GridView(this);
Now that our Activity is complete we will see the ListAdapter class that is processing each image and helps loading fast.
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import android.content.Context;
import android.content.res.Resources;
import android.os.AsyncTask;
import android.util.LruCache;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridLayout.LayoutParams;
import android.widget.GridView;
import android.widget.ImageView;
public class ListAdapter extends BaseAdapter {
    Context context;
    ArrayList items;
    private LruCache mMemoryCache;
    public ListAdapter(Context context, ArrayList items) {
        this.context = context;
        this.items = items;
        // Get memory class of this device, exceeding this amount will throw an
        // OutOfMemory exception.
        final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
        // Use 1/8th of the available memory for this memory cache.
        final int cacheSize = maxMemory / 8;
        mMemoryCache = new LruCache(cacheSize) {
            protected int sizeOf(String key, Bitmap bitmap) {
                // The cache size will be measured in bytes rather than number
                // of items.
                return bitmap.getByteCount();
    public int getCount() {
        return items.size();
    public Object getItem(int arg0) {
        return items.get(arg0);
    public long getItemId(int arg0) {
        return arg0;
    public View getView(int arg0, View convertView, ViewGroup arg2) {
        ImageView img = null;
        if (convertView == null) {
            img = new ImageView(context);
            img.setLayoutParams(new GridView.LayoutParams(
                    LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
        } else {
            img = (ImageView) convertView;
        int resId = context.getResources().getIdentifier(items.get(arg0),
                "drawable", context.getPackageName());
        loadBitmap(resId, img);
        return img;
    public void loadBitmap(int resId, ImageView imageView) {
        if (cancelPotentialWork(resId, imageView)) {
            final BitmapWorkerTask task = new BitmapWorkerTask(imageView);
    static class AsyncDrawable extends BitmapDrawable {
        private final WeakReference bitmapWorkerTaskReference;
        public AsyncDrawable(Resources res, Bitmap bitmap,
                BitmapWorkerTask bitmapWorkerTask) {
            super(res, bitmap);
            bitmapWorkerTaskReference = new WeakReference(
        public BitmapWorkerTask getBitmapWorkerTask() {
            return bitmapWorkerTaskReference.get();
    public static boolean cancelPotentialWork(int data, ImageView imageView) {
        final BitmapWorkerTask bitmapWorkerTask = getBitmapWorkerTask(imageView);
        if (bitmapWorkerTask != null) {
            final int bitmapData =;
            if (bitmapData != data) {
                // Cancel previous task
            } else {
                // The same work is already in progress
                return false;
        // No task associated with the ImageView, or an existing task was
        // cancelled
        return true;
    private static BitmapWorkerTask getBitmapWorkerTask(ImageView imageView) {
        if (imageView != null) {
            final Drawable drawable = imageView.getDrawable();
            if (drawable instanceof AsyncDrawable) {
                final AsyncDrawable asyncDrawable = (AsyncDrawable) drawable;
                return asyncDrawable.getBitmapWorkerTask();
        return null;
    public void addBitmapToMemoryCache(String key, Bitmap bitmap) {
        if (getBitmapFromMemCache(key) == null) {
            mMemoryCache.put(key, bitmap);
    public Bitmap getBitmapFromMemCache(String key) {
        return (Bitmap) mMemoryCache.get(key);
    class BitmapWorkerTask extends AsyncTask {
        public int data = 0;
        private final WeakReference imageViewReference;
        public BitmapWorkerTask(ImageView imageView) {
            // Use a WeakReference to ensure the ImageView can be garbage
            // collected
            imageViewReference = new WeakReference(imageView);
        // Decode image in background.
        protected Bitmap doInBackground(Integer... params) {
            data = params[0];
            final Bitmap bitmap = decodeSampledBitmapFromResource(
                    context.getResources(), data, 100, 100);
            addBitmapToMemoryCache(String.valueOf(params[0]), bitmap);
            return bitmap;
        // Once complete, see if ImageView is still around and set bitmap.
        protected void onPostExecute(Bitmap bitmap) {
            if (imageViewReference != null && bitmap != null) {
                final ImageView imageView = imageViewReference.get();
                if (imageView != null) {
    public static Bitmap decodeSampledBitmapFromResource(Resources res,
            int resId, int reqWidth, int reqHeight) {
        // First decode with inJustDecodeBounds=true to check dimensions
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeResource(res, resId, options);
        // Calculate inSampleSize
        options.inSampleSize = calculateInSampleSize(options, reqWidth,
        // Decode bitmap with inSampleSize set
        options.inJustDecodeBounds = false;
        return BitmapFactory.decodeResource(res, resId, options);
    public static int calculateInSampleSize(BitmapFactory.Options options,
            int reqWidth, int reqHeight) {
        // Raw height and width of image
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;
        if (height > reqHeight || width > reqWidth) {
            // Calculate ratios of height and width to requested height and
            // width
            final int heightRatio = Math.round((float) height
                    / (float) reqHeight);
            final int widthRatio = Math.round((float) width / (float) reqWidth);
            // Choose the smallest ratio as inSampleSize value, this will
            // guarantee
            // a final image with both dimensions larger than or equal to the
            // requested height and width.
            inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
        return inSampleSize;


  1. Hello Great post thanks
    I'm also interested on the modified version of this sample for using it to download from a URL and caching it in the disk and Memory
    Could you please send me the source of that version?
    Thanks in advance, and have a nice day :)

  2. The code is great at speeding up loading in the grid. Since you're using the same picture perhaps you haven't noticed a problem with it. Or at least I'm having trouble when loading multiple images (1500 to be precise) into the grid. As I scroll down, multiple mirages (previously visualized images) stay loaded, and then update to the actual ones. I don't know how should I modify the code. The only thing I changed was the BitmapFactory.decodeResource, to BitmapFactory.decodeFile to load an array list of files that points to a single folder. Any ideas? Thanks!

  3. The code is great at speeding up loading in the grid. Since you're using the same picture perhaps you haven't noticed a problem with it. Or at least I'm having trouble when loading multiple images (1500 to be precise) into the grid. As I scroll down, multiple mirages (previously visualized images) stay loaded, and then update to the actual ones. I don't know how should I modify the code. The only thing I changed was the BitmapFactory.decodeResource, to BitmapFactory.decodeFile to load an array list of files that points to a single folder.

  4. This comment has been removed by the author.


Post a Comment

Popular posts from this blog

Passing Images between Activities in Android

in First Activity:
Intent intent=new Intent(FirstClass.this, SecondClass.class); Bundle bundle=new Bundle(); bundle.putInt("image",R.drawable.ic_launcher); intent.putExtras(bundle); startActivity(intent); in Second Acticity:
Bundle bundle=this.getIntent().getExtras(); int pic=bundle.getInt("image"); v.setImageResource(pic);another method:
in First Activity:
Drawable drawable=imgv.getDrawable(); Bitmap bitmap= ((BitmapDrawable)drawable).getBitmap(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos); byte[] b = baos.toByteArray(); Intent intent=new Intent(Passimage.this,myclass.class); intent.putExtra("picture", b); startActivity(intent); in Second Acticity:
Bundle extras = getIntent().getExtras(); byte[] b = extras.getByteArray("picture"); Bitmap bmp = BitmapFactory.decodeByteArray(b, 0, b.length); Image…

Get a single record from SQLite in ANDROID

in DATABASE HELPER class: String[] coloumns = new String[] { KEY_ROWID, KEY_NAME, KEY_NICKNAME }; // calling elements in an array Cursor c = db.query(DATABASE_TABLE, coloumns, KEY_ROWID + "=" + l,null, null, null, null); if (c != null) { c.moveToFirst(); String name = c.getString(1); // since name is in position 1 ie second coloumn return name; } return null; in : String s =editinfo.getText().toString(); long l=Long.parseLong(s); DBAdapter adapter=new DBAdapter(SQliteExample.this);; String returnedname=adapter.returnName(l); String returnednickname=adapter.returnickname(l); adapter.close(); editName.setText(returnedname); editNickName.setText(returnednickname);

TextView Animation or Alpha animation (FadeIn , FadeOut) in ANDROID

An Alpha Animation is animation that controls the alpha level of an object, i.e. fading it in and out. In Android, you can apply that fading effect to almost anything, from simple text, to images, buttons, check boxes, etc…

This can be done both from xml and from java class.

Here I will explain a simple way to give a FadeIn and FadeOut for a textview on button click.. public class Textviewanimation extends Activity { Animation fadeIn,fadeOut; TextView tv; Button startanimation; Boolean fadeflag=true; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_textviewanimation); tv=(TextView) findViewById(; startanimation=(Button) findViewById(; fadeIn = new AlphaAnimation(0.0f , 1.0f ) ; fadeIn.setDuration(1200); fadeIn.setFillAfter(true); fadeOut = new AlphaAnimation(1.0f , 0.0f); fadeOut.setDurati…