Thursday, May 19, 2016

Android Studio Java Out of Memory Error




Recently i was coding in android studio and found that when i tried to import an image into an app that i built that the app would crash with an out of memory error.  So i did some research on the issue and ended up on github with some helpful tutorials.

This tip is helpful but could prove problematic.
Got a quick Solution
<application
     android:largeHeap="true" >
put into appplication tag in manifest file.
So i tried this one.
 public static Bitmap decodeFile(File f,int WIDTH,int HIGHT){
 try {
     //Decode image size
     BitmapFactory.Options o = new BitmapFactory.Options();
     o.inJustDecodeBounds = true;
     BitmapFactory.decodeStream(new FileInputStream(f),null,o);

     //The new size we want to scale to
     final int REQUIRED_WIDTH=WIDTH;
     final int REQUIRED_HIGHT=HIGHT;
     //Find the correct scale value. It should be the power of 2.
     int scale=1;
     while(o.outWidth/scale/2>=REQUIRED_WIDTH && o.outHeight/scale/2>=REQUIRED_HIGHT)
         scale*=2;

     //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;
}
Which would work if i knew how to use decodeFile in my code.
Solution:
Finally i was led to this link Android Developer Site Which had a Android program that i downloaded and studied to find the solution.  If you are like me and find this error just go to the developer site and study the code.  
Thanks for reading.

No comments:

Post a Comment

Featured Post

Washington State Poisonous Toad

The Western Toad pictured above can be green or brown and is always covered in warts.  (This is the frog he tried to eat) One w...