FATAL EXCEPTION: main java.lang.OutOfMemoryError at android.graphics.BitmapFactory.nativeDecodeStream(Native Method)

后端 未结 4 1137
时光取名叫无心
时光取名叫无心 2021-01-15 04:42

I keep getting this error when I run my app. The app will compile fine and once I start interacting with it (ImageSlider) sometimes it breaks and comes up with that message.

4条回答
  •  时光取名叫无心
    2021-01-15 05:15

    if anyone trying to get images from sqlite and getting outOfMemory error try following :

    cursor = adapter.getAllrecords(); //get your table records in cursor
    
    //moving to the current position in cursor 
    cursor.moveToPosition(position);
    
    byte [] image = cursor.getBlob(cursor.getColumnIndex("image"));
    
     BitmapFactory.Options options = new  BitmapFactory.Options();
     options.inJustDecodeBounds = true;
     bitmapImage = BitmapFactory.decodeByteArray(image, 0, image.length, options);
     imageView.setImageBitmap(decodeSampledBitmapFromResource(80, 80));//pass height and             
                                                          //width as per your requirement 
    
    
    
    public  int calculateInSampleSize( BitmapFactory.Options options, int reqWidth, int     
    reqHeight) {
            // Raw height and width of image
            final int height = options.outHeight;
            final int width = options.outWidth;
            int inSampleSize = 1;
    
            if (height > reqHeight || width > reqWidth) {
    
                final int halfHeight = height / 2;
                final int halfWidth = width / 2;
    
    // Calculate the largest inSampleSize value that is a power of 2 and keeps both
    // height and width larger than the requested height and width.
                 while ((halfHeight / inSampleSize) > reqHeight
                        && (halfWidth / inSampleSize) > reqWidth) {
                    inSampleSize *= 2;
                }
            }
    
            return inSampleSize;
        }
            public  Bitmap decodeSampledBitmapFromResource(int reqWidth, int reqHeight) {
    
                // First decode with inJustDecodeBounds=true 
                    to check dimensions
                final BitmapFactory.Options options = new BitmapFactory.Options();
                options.inJustDecodeBounds = true;
                BitmapFactory.decodeByteArray(image, 0, image.length, options);
    
                // Calculate inSampleSize
                options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
    
                // Decode bitmap with inSampleSize set
                options.inJustDecodeBounds = false;
                return BitmapFactory.decodeByteArray(image, 0, image.length, options);
            }
    

    this code worked for me..however according to developer guideliness we should handle image related task using AsyncTask...we should not run it on UI thread.

提交回复
热议问题