Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OutOfMemoryError when loading an image

I have a simple page that displays an image.The source is a URL

   var img = new Image ();
    var source = new UriImageSource {
        Uri = new Uri (string.Format ("http://xxxx.com/imagem/?{0}", url)),
            CachingEnabled = false
        };
        img .Source = source;

but when I access this page (), the fourth time or the fifth it, I get this error

java.lang.OutOfMemoryError
    at android.graphics.Bitmap.nativeCreate(Native Method)
    at android.graphics.Bitmap.createBitmap(Bitmap.java:928)
    at android.graphics.Bitmap.createBitmap(Bitmap.java:901)
    at android.graphics.Bitmap.createBitmap(Bitmap.java:868)
    at md5530bd51e982e6e7b340b73e88efe666e.ButtonDrawable.n_draw(Native Method)
    at 340b73e88efe666e.ButtonDrawable.draw(ButtonDrawable.java:49)
    at android.view.View.draw(View.java:15235)
    at android.view.View.getDisplayList(View.java:14141).....
like image 675
AMb Avatar asked Jun 26 '15 18:06

AMb


People also ask

How glides solves the out of memory oom issue?

into(imageView); Glide knows the dimension of the imageView as it takes the imageView as a parameter. Glide down-samples the image without loading the whole image into the memory. This way, the bitmap takes less memory, and the out of memory error is solved.

How do you handle bitmaps in Android as it takes too much memory?

Choose the most appropriate decode method based on your image data source. These methods attempt to allocate memory for the constructed bitmap and therefore can easily result in an OutOfMemory exception. Each type of decode method has additional signatures that let you specify decoding options via the BitmapFactory.


1 Answers

We ran into a very similar issue. It appears Xamarin has released some guidance on the issue, but it's not really geared towards Xamarin Forms. Basically, before setting the source of the image, you need to decide whether it should be scaled down, and do it manually. This will likely require a Custom Renderer.

Seems like something Xamarin Forms should do for us, but sometimes you have to take the bad with the good I suppose.

Here is a discussion on the Xamarin Forums regarding this issue.

Update: I just noticed you said that this happens only after the 4th or 5th time the page is loaded. We created a workaround on the page that solved the issue. Basically, you have to set the image's Source back to null and force a garbage collection when the page is disappearing. Like this:

protected override void OnDisappearing ()
{
    base.OnDisappearing ();
    img.Source = null;
    GC.Collect ();
}
like image 128
Greg Ferreri Avatar answered Oct 11 '22 04:10

Greg Ferreri