386

I want to show the Bitmap image in ImageView from sd card which is stored already. After run my application is crash and getting OutOfMemoryError error of:

(java.lang.OutOfMemoryError: Failed to allocate a 23970828 byte allocation with 2097152 free bytes and 2MB until OOM)

I have no idea or why its out of memory. I think my image size is very large so I tried to change it.

Iterator<String> it = imageArray.iterator();
while (it.hasNext()) {
  Object element = it.next();
  String objElement = element.toString();
  Log.e("objElement ", " = " + objElement);
  final ImageView imageView = new ImageView (getContext());
  final ProgressBar pBar = new ProgressBar(getContext(), null, 
                                           android.R.attr.progressBarStyleSmall);
  imageView.setTag(it);
  pBar.setTag(it);

  imageView.setImageResource(R.drawable.img_placeholder);
  pBar.setVisibility(View.VISIBLE);

  if (objElement.endsWith(mp3_Pattern)) {
     Log.e("Mp3 ", " ends with ");
     pBar.setVisibility(View.GONE);
     imageView.setImageResource(R.drawable.audio_control);
  }
  if (objElement.endsWith(png_Pattern)) {
     Bitmap bitmap = BitmapFactory.decodeFile(objElement);
     int size = Math.min(bitmap.getWidth(), bitmap.getHeight());
     int x = (bitmap.getWidth() - size) / 2;
     int y = (bitmap.getHeight() - size) / 2;
     Bitmap bitmap_Resul = Bitmap.createBitmap(bitmap, x, y, size, size);
     Log.e("bitmap_Resul "," = "+ bitmap_Resul);

     if (bitmap_Resul != bitmap) {
        bitmap.recycle();
     }
     imageView.setImageBitmap(bitmap_Resul);
     Log.e("png_Pattern ", " ends with ");
     Log.e(" bitmap "," = " + bitmap);
  }

  holder.linearLayout.addView(imageView);
  holder.linearLayout.addView(pBar);

The log cat information:

08-27 14:11:15.307    1857-1857/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.example.tazeen.classnkk, PID: 1857
    java.lang.OutOfMemoryError: Failed to allocate a 23970828 byte allocation with 2097152 free bytes and 2MB until OOM
            at dalvik.system.VMRuntime.newNonMovableArray(Native Method)
            at android.graphics.Bitmap.nativeCreate(Native Method)
            at android.graphics.Bitmap.createBitmap(Bitmap.java:812)
            at android.graphics.Bitmap.createBitmap(Bitmap.java:789)
            at android.graphics.Bitmap.createBitmap(Bitmap.java:709)
            at android.graphics.Bitmap.createBitmap(Bitmap.java:634)
            at com.example.tazeen.classnkk.AllPosts_Page$MyListAdapter.getView(AllPosts_Page.java:357)
            at android.widget.AbsListView.obtainView(AbsListView.java:2347)
            at android.widget.ListView.makeAndAddView(ListView.java:1864)
            at android.widget.ListView.fillDown(ListView.java:698)
            at android.widget.ListView.fillFromTop(ListView.java:759)
            at android.widget.ListView.layoutChildren(ListView.java:1659)
            at android.widget.AbsListView.onLayout(AbsListView.java:2151)
            at android.view.View.layout(View.java:15671)
            at android.view.ViewGroup.layout(ViewGroup.java:5038)
            at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1703)
            at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1557)
            at android.widget.LinearLayout.onLayout(LinearLayout.java:1466)
            at android.view.View.layout(View.java:15671)
            at android.view.ViewGroup.layout(ViewGroup.java:5038)
            at android.widget.FrameLayout.layoutChildren(FrameLayout.java:579)
            at android.widget.FrameLayout.onLayout(FrameLayout.java:514)
            at android.view.View.layout(View.java:15671)
            at android.view.ViewGroup.layout(ViewGroup.java:5038)
            at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1703)
            at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1557)
            at android.widget.LinearLayout.onLayout(LinearLayout.java:1466)
            at android.view.View.layout(View.java:15671)
            at android.view.ViewGroup.layout(ViewGroup.java:5038)
            at android.widget.FrameLayout.layoutChildren(FrameLayout.java:579)
            at android.widget.FrameLayout.onLayout(FrameLayout.java:514)
            at android.view.View.layout(View.java:15671)
            at android.view.ViewGroup.layout(ViewGroup.java:5038)
            at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2086)
            at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1843)
            at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1061)
            at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5885)
            at android.view.Choreographer$CallbackRecord.run(Choreographer.java:767)
            at android.view.Choreographer.doCallbacks(Choreographer.java:580)
            at android.view.Choreographer.doFrame(Choreographer.java:550)
            at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:753)
            at android.os.Handler.handleCallback(Handler.java:739)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5257)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Cœur
  • 32,421
  • 21
  • 173
  • 232
androidTag
  • 4,523
  • 7
  • 15
  • 24

31 Answers31

581

OutOfMemoryError is the most common problem that occurs in android while especially dealing with bitmaps. This error is thrown by the Java Virtual Machine (JVM) when an object cannot be allocated due to lack of memory space and also, the garbage collector cannot free some space.

As mentioned by Aleksey, you can add the below entities in your manifest file android:hardwareAccelerated="false" , android:largeHeap="true" it will work for some environments.

<application
    android:allowBackup="true"
    android:hardwareAccelerated="false"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:largeHeap="true"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">

you should definitely read some of Androids Developer concept's, especially here:Displaying Bitmaps Efficiently

Read all 5 topics and rewrite your code again. If it still doesn't work we will be happy to see what you've done wrong with the tutorial material.

Here some of the possible answers for these type of errors in SOF

Android: BitmapFactory.decodeStream() out of memory with a 400KB file with 2MB free heap

How to solve java.lang.OutOfMemoryError trouble in Android

Android : java.lang.OutOfMemoryError

java.lang.OutOfMemoryError

Solution for OutOfMemoryError: bitmap size exceeds VM budget

Edit: From the comments of @cjnash

For anyone that still had crashes after they added this line, try sticking your image into your res/drawable-xhdpi/ folder instead of your res/drawable/ and this should resolve this issue

King of Masses
  • 16,881
  • 4
  • 57
  • 75
  • 1
    Could you please post how you eventually solved the issue? Because i have the same problem... Actually you can add in your manifest this lines android:hardwareAccelerated="false" , android:largeHeap="true" it is working for some situations, but be aware the that another part of code can be arguing with this... – Aleksey Timoshchenko Apr 20 '16 at 06:37
  • So I have a map, where I want to show polylines. I want arrowheads on those polylines to show direction. The arrowheads are implemented by taking an image of an upward facing arrow, rotating, and pasting as a Marker. I have about 500 of these Markers. When I change zoom, I remove all Markers, and create newer ones, in the amount appropriate to the zoom level. However the old ones are not garbage collected, so after a few zoom ins and outs, I get OutOfMemoryError. `LruCache` for Bitmaps didn't help. What else can I do to optimze? – f.khantsis Sep 12 '16 at 20:37
  • 9
    app navigation is becoming very slow after adding this. – Uma Achanta Dec 30 '16 at 07:47
  • 14
    android:hardwareAccelerated="false" freezing your app – Rahim Rahimov Apr 15 '17 at 15:00
  • 3
    For anyone that still had crashes after they added this line, try sticking your image into your res/drawable-xhdpi/ folder instead of your res/drawable/ and it might resolve your issue. – cjnash Aug 01 '17 at 15:45
  • 1
    is android:hardwareAccelerated="false" , android:largeHeap="true" best practices or is it some sort of a hack? – Red M Nov 19 '17 at 00:24
  • 8
    why would you suggest android:hardwareAccelerated="false ? what is the benefit of it? – Emil Dec 13 '17 at 16:04
  • 1
    Very helpful answer. Solved my problem. Thanks. – Omid1989 Mar 12 '18 at 17:14
  • [https://stackoverflow.com/questions/11820266/android-bitmapfactory-decodestream-out-of-memory-with-a-400kb-file-with-2mb-f](https://stackoverflow.com/questions/11820266/android-bitmapfactory-decodestream-out-of-memory-with-a-400kb-file-with-2mb-f) `BitmapFactory.Options options = new BitmapFactory.Options(); options.inSampleSize = 2; Bitmap bitmap = BitmapFactory.decodeStream(stream, null, options);` – Nitin Karale Sep 21 '18 at 13:19
  • Not working. still getting the same error after adding this. – Vasu Oct 08 '18 at 07:16
  • @King of masses I am not facing this issue with rerspect to BitMapFactory, Its something as follows. I am unable to reproduce it. Caused by: java.lang.OutOfMemoryError: Failed to allocate a 11144 byte allocation with 10640 free bytes and 6KB until OOM at java.util.Arrays.copyOf(Arrays.java:3352) at java.lang.AbstractStringBuilder.expandCapacity(AbstractStringBuilder.java:130) – Kaveri Jan 30 '19 at 07:02
  • 1
    When I add android:hardwareAccelerated="false" all the default animations like a button press, Fab Press will be disabled. – Rehan Sarwar Apr 05 '19 at 07:33
  • worked for me, but the app was a bit slow. I think that this is good as a temporary solution, what I did was reduce the size of my Images – Doilio Matsinhe May 31 '19 at 13:51
  • 4
    Setting **android:hardwareAccelerated="false"**, stopped many animations of my app like shadow and elevation. – Nilesh Rathore Jan 22 '20 at 07:52
  • I have images selected from device storage and that's why it can be of any size,now i don't want to resize image, plus i will perform many operations on it, now can you please tell me how can i avoid this error? (remember i don't want to loose image quality so forgot about `BitmapFactory.Options` and it's other options) – Vivek Thummar Feb 26 '21 at 12:26
92

have you tried adding this to your manifest under applications? android:largeHeap="true"?

like this

  <application
      android:name=".ParaseApplication"
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:theme="@style/AppTheme"
      android:largeHeap="true" >
V-rund Puro-hit
  • 5,270
  • 8
  • 27
  • 48
TSG
  • 1,081
  • 6
  • 10
32

For me, the problem was that my .png file was being de-compressed to be a really huge bitmap in memory, because the image had very large dimensions (even though the file size was tiny).

So the fix was to simply resize the image :)

petrus-jvrensburg
  • 1,183
  • 13
  • 18
  • 4
    this is the correct solution, because I firstly tried above solutions, but after applying `android:hardwareAccelerated="false"`, some animations like layout shadow were not working. But after resizing all the problems were solved thank you! +1 for this hint! – Kaushal28 May 29 '17 at 05:29
  • 1
    this fixed my problem. Thank you @petrus – Hùng Nguyễn Sep 10 '17 at 04:12
32

Actually you can add in your manifest these lines android:hardwareAccelerated="false" , android:largeHeap="true" it is working for some situations, but be aware that the other part of code can be arguing with this.

<application
    android:allowBackup="true"
    android:hardwareAccelerated="false"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:largeHeap="true"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
onexf
  • 3,244
  • 3
  • 20
  • 34
Aleksey Timoshchenko
  • 3,364
  • 1
  • 33
  • 61
29

This should work

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

 mBitmapSampled = BitmapFactory.decodeFile(mCurrentPhotoPath,options);
Akshay komarla
  • 694
  • 10
  • 20
13

Resize your image before setup to ImageView like this:

Bitmap.createScaledBitmap(_yourImageBitmap, _size, _size, false);

where size is actual size of ImageView. You can reach size by measuring:

imageView.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED), MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));

and use next size imageView.getMeasuredWidth() and imageView.getMeasuredHeight() for scaling.

Vinoth Vino
  • 6,991
  • 3
  • 54
  • 59
Vladimir Eremeev
  • 253
  • 1
  • 10
  • I have tried with this android:largeHeap="true" but getting same error – androidTag Aug 27 '15 at 09:46
  • A further example of why this won't necessarily work (using private app storage): Placing a bitmap in res/drawable/ can give the same error but it won't happen every time. Placing same bitmap into res/drawable-xhdpi/ will no longer have the error. So as an answer, its not correct by itself. – CmosBattery Apr 22 '16 at 13:59
10

Use Glide Library and Override size to less size;

Glide.with(mContext).load(imgID).asBitmap().override(1080, 600).into(mImageView);
Vinoth Vino
  • 6,991
  • 3
  • 54
  • 59
Mahdi Azadbar
  • 1,221
  • 3
  • 14
  • 23
9

I got below error

"E/art: Throwing OutOfMemoryError "Failed to allocate a 47251468 byte allocation with 16777120 free bytes and 23MB until OOM"

after adding android:largeHeap="true" in AndroidManifest.xml then I rid of all the errors

<application
    android:allowBackup="true"
    android:icon="@mipmap/guruji"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:largeHeap="true"
    android:theme="@style/AppTheme">
Vinoth Vino
  • 6,991
  • 3
  • 54
  • 59
Sai Gopi Me
  • 9,800
  • 1
  • 65
  • 43
7

Issue : Failed to allocate a 37748748 byte allocation with 16777120 free bytes and 17MB until OOM

Solution : 1.open your manifest file 2. inside application tag just add below two lines

 android:hardwareAccelerated="false"
 android:largeHeap="true"

Example :

 <application
        android:allowBackup="true"
        android:hardwareAccelerated="false"
        android:largeHeap="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
King of Masses
  • 16,881
  • 4
  • 57
  • 75
Kishore Reddy
  • 2,002
  • 16
  • 14
6

I have resolved this problem by resizing the image to lower size. I am using xamarin form. decreasing the size of the PNG image resolved the problem.

maxspan
  • 10,656
  • 12
  • 61
  • 88
6

I have found that images in the 'drawable' folder will get converted to a much larger image on high def phones. For example, a 200k image will be resampled to a higher res, like 800k or 32000k. I had to discover this on my own and to date have not seen documentation for this heap memory trap. To prevent this I put everything in a drawable-nodpi folder (in addition to using 'options' in BitmapFactory based on the particular device heap). I can't afford to have the size of my app bloated with multiple drawable folders, particularly as the range of screen defs is so vast now. The tricky thing is studio now doesn't specifically indicate the 'drawable-nodpi' folder as such in the project view, it just shows a 'drawable' folder. If you're not careful, when you drop an image to this folder in studio, it won't actually get dropped into the drawable-nodpi:

Careful here 'backgroundtest' did not actually go to drawable-nodpi and will 
be resampled higher, such as 4x or 16x of the original dimensions for high def screens.

enter image description here

Be sure to click down to the nodpi folder in the dialogue, as the project view won't show you all drawable folders separately like it used to, so it won't be immediately apparent that it went to wrong one. Studio recreated the vanilla 'drawable' at some point for me after I had deleted it long ago:

enter image description here

Androidcoder
  • 3,337
  • 4
  • 27
  • 38
5

This worked for me: just move images from drawable folder to drawable-hdpi.

Hossein Amini
  • 692
  • 8
  • 20
4

Soluton try this in your Manifest File and use Glide Library

compile 'com.github.bumptech.glide:glide:3.7.0'

    **Use Glide Library and Override size to less size;**

 if (!TextUtils.isEmpty(message.getPicture())) {
            Glide.with(mContext).load(message.getPicture())
                    .thumbnail(0.5f)
                    .crossFade()
                    .transform(new CircleTransform(mContext))
                    .diskCacheStrategy(DiskCacheStrategy.ALL)
                    .into(holder.imgProfile);
        } 

android:hardwareAccelerated="false"

android:largeHeap="true"

<application
    android:allowBackup="true"
    android:hardwareAccelerated="false"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:largeHeap="true"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">

Use this library

  compile 'com.github.bumptech.glide:glide:3.7.0'   

Its Working Happy Coding

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Paint;

import com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool;
import com.bumptech.glide.load.resource.bitmap.BitmapTransformation;


public class CircleTransform extends BitmapTransformation {
    public CircleTransform(Context context) {
        super(context);
    }

    @Override
    protected Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) {
        return circleCrop(pool, toTransform);
    }

    private static Bitmap circleCrop(BitmapPool pool, Bitmap source) {
        if (source == null) return null;

        int size = Math.min(source.getWidth(), source.getHeight());
        int x = (source.getWidth() - size) / 2;
        int y = (source.getHeight() - size) / 2;

        // TODO this could be acquired from the pool too
        Bitmap squared = Bitmap.createBitmap(source, x, y, size, size);

        Bitmap result = pool.get(size, size, Bitmap.Config.ARGB_8888);
        if (result == null) {
            result = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
        }

        Canvas canvas = new Canvas(result);
        Paint paint = new Paint();
        paint.setShader(new BitmapShader(squared, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP));
        paint.setAntiAlias(true);
        float r = size / 2f;
        canvas.drawCircle(r, r, r, paint);
        return result;
    }

    @Override
    public String getId() {
        return getClass().getName();
    }
}
Shreyas Sanil
  • 221
  • 2
  • 13
Keshav Gera
  • 8,200
  • 1
  • 56
  • 43
4

add this to your manifest under applications? android:largeHeap="true"

3

I had the problem too.

Same with most of others above. The problem is caused by huge image.

Just resize some images, and no need to change any code.

Mike Yan
  • 1,486
  • 2
  • 16
  • 20
3

In some cases (e.g. operations in a loop) garbage collector is slower than your code. You can use a helper method from this answer to wait for garbage collector.

Zon
  • 12,838
  • 4
  • 69
  • 82
3

You have to change the size of object in drawable. It's too big for android to display. e.g. If you are setting image try image with less pixels. It works for me. Thanks. :)

3

Your app is crashing because your image size (in MB Or KB) is too large so it is not allocating space for that. So before pasting your image in drawable just reduce the size.

OR

You can add Following in application tag at Manifest.xml

 android:hardwareAccelerated="false"
    android:largeHeap="true"
    android:allowBackup="true"

After Adding this App will not Crash.

  • always use less sizes images in App.
  • If You adding large sizes of images in app , you should add above syntex, but App size will increase.
rhaldar
  • 951
  • 9
  • 6
3

My problem solved after adding

 dexOptions {
        incremental true
        javaMaxHeapSize "4g"
        preDexLibraries true
        dexInProcess = true
    }

in Build.Gradle file

Midhilaj
  • 3,929
  • 6
  • 29
  • 58
3
Last but not the least....

Try Method One:

Simple Add these lines of code in the gradle file

dexOptions {
        incremental true
        javaMaxHeapSize "4g"
     }

Example:

android {
    compileSdkVersion XX
    buildToolsVersion "28.X.X"

    defaultConfig {
        applicationId "com.example.xxxxx"
        minSdkVersion 14
        targetSdkVersion 19
    }

dexOptions {
        incremental true
        javaMaxHeapSize "4g"
     }
}

*******************************************************************

Method Two:

Add these two lines of code in manifest file...

android:hardwareAccelerated="false" 
android:largeHeap="true"

Example:

<application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:hardwareAccelerated="false"
        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>
    </application>

It will Work for sure any of these cases.....
3

If android:largeHeap="true" didn't work for you then

1:

Image Compression. I am using this website

2:

Convert images to mdpi,hdpi, xhdpi, xxhdpi, xxxhdpi. I am using this webiste

Don't remove android:largeHeap="true"!

Shahzad Afridi
  • 1,688
  • 19
  • 22
2

I'm a newbie in android developing but I hope my solution helps, it works on my condition perfectly. Im using Imageview and set it's background to "src" because im trying to make a frame animation. I got the same error but when I tried to code this it worked

int ImageID = this.Resources.GetIdentifier(questionPlay[index].Image.ToLower(), "anim", PackageName);
            imgView.SetImageResource(ImageID);
            AnimationDrawable animation = (AnimationDrawable)imgView.Drawable;
            animation.Start();
            animation.Dispose();
2
Bitmap image =((BitmapDrawable)imageView1.getDrawable()).getBitmap();

ByteArrayOutputStream byteArrayOutputStream=new ByteArrayOutputStream();

image.compress(Bitmap.CompressFormat.JPEG,50/100,byteArrayOutputStream);

50/100 if one uses 100 then original resolution can stopped the Apps for out of memory.

if 50 or less than 100 this will be 50% or less than 100 resolution so this will prevent from out of memory problem

King of Masses
  • 16,881
  • 4
  • 57
  • 75
RAHINUR RAHMAN
  • 121
  • 1
  • 5
2

Use an image loading library like Picasso or Glide. Using these libraries will prevent crashes in the future.

Community
  • 1
  • 1
Vladyslav Panchenko
  • 1,399
  • 1
  • 14
  • 22
2

I don't really recommend editing manifest like this

android:hardwareAccelerated="false" , android:largeHeap="true"

These options cause not smooth animation effect on your app. Moreover 'liveData' or changing your local DB(Sqlite, Room) activate slowly. It is bad for user experience.

So I recommend RESIZE bitmap

Below is the sample code

fun resizeBitmap(source: Bitmap): Bitmap {
      val maxResolution = 1000    //edit 'maxResolution' to fit your need
      val width = source.width
      val height = source.height
      var newWidth = width
      var newHeight = height
      val rate: Float

            if (width > height) {
                if (maxResolution < width) {
                    rate = maxResolution / width.toFloat()
                    newHeight = (height * rate).toInt()
                    newWidth = maxResolution
                }
            } else {
                if (maxResolution < height) {
                    rate = maxResolution / height.toFloat()
                    newWidth = (width * rate).toInt()
                    newHeight = maxResolution
                }
            }
            return Bitmap.createScaledBitmap(source, newWidth, newHeight, true)
 }
J.Dragon
  • 450
  • 4
  • 10
1

If uploading an image, try reducing the image quality, which is the second parameter of the Bitmap. This was the solution in my case. Previously it was 90, then I tried with 60 (as it is in the code below now).

Bitmap yourSelectedImage = BitmapFactory.decodeStream(imageStream);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
finalBitmap.compress(Bitmap.CompressFormat.JPEG,60,baos);
byte[] b = baos.toByteArray();
Teo Mihaila
  • 127
  • 1
  • 2
  • 17
1

Try the simplest one. Maybe Your app is crashing because your image size (in MB) is too large so it is not allocating space for that. So before pasting your image in drawable just reduce the size by any viewer software or if you are taking image from gallery at the run time than before saving it compress your bitmap. It worked for me. definitely for u will be.

yakobom
  • 2,630
  • 1
  • 23
  • 31
neens
  • 75
  • 7
1

I ran into this problem when I didn't kill off my old activity when moving on to a new activity. I fixed it with finish();

    Intent goToMain = new Intent(this,MainActivity.class);
    startActivity(goToMain);
    finish();
Jason Hu
  • 59
  • 3
1
stream = activity.getContentResolver().openInputStream(uri);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.RGB_565;

bitmap = BitmapFactory.decodeStream(stream, null, options);
int Height = bitmap.getHeight();
int Width = bitmap.getWidth();
enter code here
int newHeight = 1000;
float scaleFactor = ((float) newHeight) / Height;
float newWidth = Width * scaleFactor;

float scaleWidth = scaleFactor;
float scaleHeight = scaleFactor;
Matrix matrix = new Matrix();
matrix.postScale(scaleWidth, scaleHeight);
resizedBitmap= Bitmap.createBitmap(bitmap, 0, 0,Width, Height, matrix, true);
bitmap.recycle();

Then in Appliaction tag, add largeheapsize="true

Pang
  • 8,605
  • 144
  • 77
  • 113
1

I suppose you want to use this image as an icon. As Android is telling you, your image is too large. What you just need to do is scale your image so that Android knows which size of the image to use and when according to screen resolution. To accomplish this, in Android Studio: 1. right click on the res folder, 2. select Image Asset 3. Select icon Type 4. Give the icon a name 5. Select Image on Asset Type 6. Trim your image Click next and finish. In your xml or source code just refer to the image which will now be located either in the layout or mipmap folder according to asset type selected. The error will go away.

1

Make android:hardwareAccelerated="false" to be activity specific. Hope that, this might solve the problem for freezing as well as animation issues. Like this...

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:largeHeap="true">
.
.
.
.
<activity android:name=".NavigationItemsFolder.GridsMenuActivityClasses.WebsiteActivity"
            android:windowSoftInputMode="adjustPan"
            android:hardwareAccelerated="false"/>
</application>
Mohd Asim
  • 306
  • 2
  • 5