java.lang.OutOfMemoryError: Failed to allocate error

1

This error is happening in my application:

  

java.lang.OutOfMemoryError: Failed to allocate

My Image Code:

URL url1 = null;
    try {
        url1 = new URL("http://www.cm-mgrande.pt" + cabecalho);
    } catch (MalformedURLException e) {
        e.printStackTrace();
    }


    try {
        InputStream input = url1.openConnection().getInputStream();
        Bitmap bmp = BitmapFactory.decodeStream(input);
        input.close();
        BufferedReader in = new BufferedReader(
                new InputStreamReader(url1.openStream()));
        in.close();
        imgcabecalho.setImageBitmap(bmp);
        imgcabecalho.setScaleType(ImageView.ScaleType.FIT_XY);
    } catch (IOException e) {
        e.printStackTrace();


    }

My Android Manifest:

<?xml version="1.0" encoding="utf-8"?>

                

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:largeHeap="true"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name=".MainActivity"
        android:label="@string/app_name" >

        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>


    <activity
        android:name=".Index"
    android:configChanges="orientation|screenSize"
        android:largeHeap="true"
        android:label="@string/app_name" >



    </activity>
</application>

    
asked by anonymous 09.07.2015 / 17:09

1 answer

1

The Bitmap is probably too large for the memory allocated by your app. The documentation recommends careful handling of bitmaps, especially memory. Here you have enough useful information .

I recommend that you create a bitmap according to the size that will be displayed. To do this you first need to mark the bitmap as inJustDecodeBounds , so you just get the information from it to scale down and not load it into memory.

    BitmapFactory.Options options = new BitmapFactory.Options();

    options.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(filePath , options );

    // faça o cálculo da sua escala
    int imageWidth = options.outWidth;
    scale   = Math.round( imageHeight / width );
    options.inSampleSize    = scale;

    //Remove marcação e inicia o trabalho no bitmap
    options.inJustDecodeBounds  = false;

    // Cria o bitmap com o tamanho reduzido
    Bitmap scaledBitmap = BitmapFactory.decodeFile(filePath , options);

This operation is expensive and I do not recommend you do it in the UI. Creates an AsyncTask or something. One tip is that there are several very good librarys that do this service. The Universal Loader works great.

I hope I have helped.

    
15.07.2015 / 04:35