Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6809471
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 26, 20262026-05-26T20:05:26+00:00 2026-05-26T20:05:26+00:00

java.lang.OutOfMemoryError: bitmap size exceeds VM budget. i am updating images to a gridview from

  • 0
java.lang.OutOfMemoryError: bitmap size exceeds VM budget.

i am updating images to a gridview from internet using this imageloader class.some times i have to download around 1000 images but getting the same error.
please help me for the same.

  public class ImageLoader {


   public static  HashMap<String, Bitmap> cache=new HashMap<String, Bitmap>();

   private File cacheDir;
   int i=0;
   File f;
   BitmapDrawable b;
    public ImageLoader(Context context){
        //Make the background thead low priority. This way it will not affect the UI performance
        photoLoaderThread.setPriority(Thread.NORM_PRIORITY-1);

       GridViewConfig.clearFilelist();
       GridViewConfig.file_list=new ArrayList<String>();


        //Find the dir to save cached images
        if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))
            cacheDir=new File(android.os.Environment.getExternalStorageDirectory(),"LazyList");
        else
            cacheDir=context.getCacheDir();
        if(!cacheDir.exists())
            cacheDir.mkdirs();
    }

    final int stub_id=R.drawable.imagelistback_106x133;
    public void DisplayImage(String url, Activity activity, ImageView imageView)
    {

        if(cache.containsKey(url))
        {

           /* if(Common.isgallery)
            {
            b=null;
            b=new BitmapDrawable(cache.get(url));
            Bitmap bb=Bitmap.createScaledBitmap(cache.get(url), 300, 300, true);
            imageView.setImageBitmap(bb);
            bb.recycle();
            }
            else
            {*/

                 imageView.setImageBitmap(cache.get(url));
           /* }*/
        }
        else
        {
            //Toast.makeText(activity, "ELSE in dISPLAY iMAGES", Toast.LENGTH_LONG).show();
            queuePhoto(url, activity, imageView);
            imageView.setImageResource(stub_id);
        }   



    }

    private void queuePhoto(String url, Activity activity, ImageView imageView)
    {
        //This ImageView may be used for other images before. So there may be some old tasks in the queue. We need to discard them. 
        photosQueue.Clean(imageView);
        PhotoToLoad p=new PhotoToLoad(url, imageView);
        synchronized(photosQueue.photosToLoad){
            photosQueue.photosToLoad.push(p);
            photosQueue.photosToLoad.notifyAll();
        }

        //start thread if it's not started yet
        if(photoLoaderThread.getState()==Thread.State.NEW)
            photoLoaderThread.start();
    }
    public void Createfile(String url)
    {
        String filename=String.valueOf(url.hashCode());
        f=new File(cacheDir, filename);
        GridViewConfig.file_list.add(f.getAbsolutePath());
    }
    public Bitmap getBitmap(String url) 
    {

        //I identify images by hashcode. Not a perfect solution, good for the demo.
        String filename=String.valueOf(url.hashCode());
        //String filename=GridViewConfig.sku_list.get(i);
        File f=new File(cacheDir, filename);
        GridViewConfig.file_list.add(f.getAbsolutePath());
        /*if(Common.firstLoading)
        {
        GridViewConfig.file_list.add(f.getAbsolutePath());
        i++;
        Log.v("gooooooooogle file list", "file list size "+i);

        }*/
        //from SD cache
        Bitmap b = decodeFile(f);
        if(b!=null)
            return b;

        //from web
        try {
            Bitmap bitmap=null;
            InputStream is=new URL(url).openStream();
            OutputStream os = new FileOutputStream(f);
            Utils.CopyStream(is, os);
            os.close();
            bitmap = decodeFile(f);
            return bitmap;
        } catch (Exception ex){
           ex.printStackTrace();
           return null;
        }
    }

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

            //Find the correct scale value. It should be the power of 2.
            final int REQUIRED_SIZE=50;
            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++;
            }
            Log.v("", "Scale"+scale);
            //decode with inSampleSize
            BitmapFactory.Options o2 = new BitmapFactory.Options();
            o2.inSampleSize=scale;
            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;
        }
    }

    PhotosQueue photosQueue=new PhotosQueue();

    public void stopThread()
    {
        photoLoaderThread.interrupt();
    }

    //stores list of photos to download
    class PhotosQueue
    {
        private Stack<PhotoToLoad> photosToLoad=new Stack<PhotoToLoad>();

        //removes all instances of this ImageView
        public void Clean(ImageView image)
        {
            for(int j=0 ;j<photosToLoad.size();){
                if(photosToLoad.get(j).imageView==image)
                    photosToLoad.remove(j);
                else
                    ++j;
            }
        }
    }

    class PhotosLoader extends Thread {
        public void run() {
            try {
                while(true)
                {
                    //thread waits until there are any images to load in the queue
                    if(photosQueue.photosToLoad.size()==0)
                        synchronized(photosQueue.photosToLoad){
                            photosQueue.photosToLoad.wait();
                        }
                    if(photosQueue.photosToLoad.size()!=0)
                    {
                        PhotoToLoad photoToLoad;
                        synchronized(photosQueue.photosToLoad){
                            photoToLoad=photosQueue.photosToLoad.pop();
                        }
                        Bitmap bmp=getBitmap(photoToLoad.url);
                        cache.put(photoToLoad.url, bmp);
                        if(((String)photoToLoad.imageView.getTag()).equals(photoToLoad.url)){
                            BitmapDisplayer bd=new BitmapDisplayer(bmp, photoToLoad.imageView);
                            Activity a=(Activity)photoToLoad.imageView.getContext();
                            a.runOnUiThread(bd);
                        }
                    }
                    if(Thread.interrupted())
                        break;
                }
            } catch (InterruptedException e) {
                //allow thread to exit
            }
        }
    }

    PhotosLoader photoLoaderThread=new PhotosLoader();

    //Used to display bitmap in the UI thread
    class BitmapDisplayer implements Runnable
    {
        Bitmap bitmap;
        ImageView imageView;
        public BitmapDisplayer(Bitmap b, ImageView i)
        {
            bitmap=b;
            imageView=i;
        }
        public void run()
        {
            if(bitmap!=null)
                /*if(Common.isgallery)
                {
                    b=null;
                    b=new BitmapDrawable(bitmap);
                    Bitmap bit=Bitmap.createScaledBitmap(bitmap, 300, 300, true);
                    imageView.setImageBitmap(bit);
                    bit.recycle();
                }
                else
                {*/
                imageView.setImageBitmap(bitmap);

                /*}*/
            else
                imageView.setImageResource(stub_id);
        }
    }

    public void clearCache() {
        //clear memory cache
        cache.clear();

        //clear SD cache
        File[] files=cacheDir.listFiles();
        for(File f:files)
            f.delete();
    }

}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-26T20:05:27+00:00Added an answer on May 26, 2026 at 8:05 pm

    I would suggest:

    • use SoftReference<Bitmap> or WeakReference<Bitmap> instead of simple Bitmap in cache. That way You won’t face OOM;
    • use options for decoding (as suggested by Awais Tariq) – inSampleSize option gives nice improvement on memory (seems already done in Your code);
    • maintain cache on sd card for downloaded images. Please refer to this question for additional options (seems already done in Your code).
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I am getting the error java.lang.OutOfMemoryError: bitmap size exceeds VM budget . This occurs
I am getting the 'java.lang.OutOfMemoryError: bitmap size exceeds VM budget' error... What I am
I'm getting a lot of these exceptions from users: java.lang.OutOfMemoryError: bitmap size exceeds VM
Possible Duplicate: OutOfMemoryError: bitmap size exceeds VM budget :- Android Im in the process
Possible Duplicate: OutOfMemoryError: bitmap size exceeds VM budget :- Android I have code like
Recently I ran into this error in my web application: java.lang.OutOfMemoryError: PermGen space It's
I get a java.lang.OutOfMemoryError: Java heap space message when reading from an 11g Oracle
I am getting this error: Exception in thread main java.lang.OutOfMemoryError: Java heap space at
I am having issue with memory after running many times my app. java.lang.OutOfMemoryError: bitmap
I get this error message as I execute my JUnit tests: java.lang.OutOfMemoryError: GC overhead

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.