retrieve image from gallery in android
I have created an Activity
where i have a Button
.
By pressing the button an android Gallery
opens. When i choose an image from the gallery it is shows it in an ImageView
of my Activity
but after choosing second time the following error occuring
01-13 17:55:25.323: ERROR/AndroidRuntime(14899): java.lang.OutOfMemoryError: bitmap size exceeds VM budget
Here is the source code i am using:
public class MyImage extends Activity {
/** Called when the activity is first created. */
Gallery gallery;
private Uri[] mUrls;
String[] mFiles=null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
File images = Environment.getDataDirectory();
File[] imagelist = images.listFiles();
mFiles = new String[imagelist.length];
for(int i= 0 ; i< imagelist.length; i++)
{
mFiles[i] = imagelist[i].getAbsolutePath();
}
mUrls = new Uri[mFiles.length];
for(int i=0; i < mFiles.length; i++)
{
mUrls[i] = Uri.parse(mFiles[i]);
}
Gallery g = (Gallery) findViewById(R.id.Gallery01);
g.setAdapter(ne开发者_Go百科w ImageAdapter(this));
g.setFadingEdgeLength(40);
}
public class ImageAdapter extends BaseAdapter{
int mGalleryItemBackground;
public ImageAdapter(Context c) {
mContext = c;
}
public int getCount(){
return mUrls.length;
}
public Object getItem(int position){
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent){
ImageView i = new ImageView(mContext);
i.setImageURI(mUrls[position]);
i.setScaleType(ImageView.ScaleType.FIT_XY);
i.setLayoutParams(new Gallery.LayoutParams(260, 210));
return i;
}
private Context mContext;
}
}
There are plenty of answer related to this. Check it out.
I have encountered this exactly same problem too. What you can do to prevent this from happening is to make sure you recycle the previous Bitmap before loading the new one. Call Bitmap.recycle() to do this. http://developer.android.com/reference/android/graphics/Bitmap.html#recycle()
I don't see where you handle the Bitmaps in you code but you get the idea?
Another thing when handling Bitmaps is to keep in ming how big they actually are when read into memory and do you really need to have that large images for your usecase. You can read the Bitmap to your app with lower sample rate if you don't need to have the full image. This saves a lot of memory.
It is very common problem. It is maybe because you are having many images, and the Android emulator heap size is small. So you have to recycle your imagebitmap each time after use.
See this question.
精彩评论