codegasmer
codegasmer

Reputation: 1468

OutOfMemory Exception for background image of a layout

I am new to android following this tutorial for creating a MEME application in android everything was working fine until I added image to my RelativeLayout background of a fragement.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="match_parent"
    android:background="@drawable/dp"
    android:id="@+id/imageOut">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="@string/topText"
        android:id="@+id/topMemeText"
        android:layout_marginTop="32dp"
        android:textColor="#FFF"
        android:gravity="center_horizontal"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true" />


    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="@string/bottomText"
        android:id="@+id/bottomMemeText"
        android:layout_marginBottom="69dp"
        android:textColor="#FFF"
        android:gravity="center_horizontal"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true" />
</RelativeLayout>

The error was

 Caused by: java.lang.OutOfMemoryError: Failed to allocate a 86687164 byte allocation with 1048576 free bytes and 63MB until OOM

I know that this problem is due to image size and I have to decode it as there are many case as I searched online and here http://developer.android.com/training/displaying-bitmaps/load-bitmap.html .But everycase I came across use a ImageView but I have a background image of the layout rather than a ImageView so I how can I get the ImageView object from layout so that I can use.

mImageView.setImageBitmap(
    decodeSampledBitmapFromResource(getResources(), R.id.myimage, 100, 100));

Thanks

Upvotes: 0

Views: 732

Answers (2)

SuperFrog
SuperFrog

Reputation: 7674

My guess is that the resizing of the image is causing your problem.

Try adding the image to drawable-xxhdpi and see if it helps.

If it doesn't try drawable-nodpi.

Upvotes: 1

Umesh Singh Kushwaha
Umesh Singh Kushwaha

Reputation: 5741

First get the bitmap 
Bitmap bitmap = decodeSampledBitmapFromResource(getResources(), R.id.myimage, 100, 100);

Convert the bitmap to drawable as follows
Drawable mDrawable = new BitmapDrawable(getResources(), bitmap);

Finally you can use mDrawable to set your relative layout background

Upvotes: 0

Related Questions