1

Before sending bitmap image to server, I compress it. And upload image operation is always successfull. But after some moment application crash

Exception:

java.lang.OutOfMemoryError: Failed to allocate a 230412 byte allocation with 168272 free bytes and 164KB until OOM

Code:

        HttpPost httpPost = new HttpPost(url);
        HttpClient httpClient = new DefaultHttpClient();
        MultipartEntity reqEntity = new MultipartEntity();
        Charset charsUTF8 = Charset.forName("UTF-8"); 
        HttpResponse httpResponse;

        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        BitmapUtils.getBitmap(context,url).compress(CompressFormat.JPEG, 10, stream);
        byte[] byteArray = stream.toByteArray();
        ByteArrayBody body = new ByteArrayBody(byteArray, name + ".jpg");

        reqEntity.addPart("photo", body);

        httpPost.setEntity(reqEntity);
        httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        String stringData = EntityUtils.toString(httpEntity);

BitmapUtils class:

    private static Uri getImageUri(String path) {
        return Uri.fromFile(new File(path));
    }
    public static Bitmap getBitmap(Context context,String path) {
        Uri uri = getImageUri(path);
        InputStream in = null;
        try {
            in = context.getContentResolver().openInputStream(uri);

            //Decode image size
            BitmapFactory.Options o = new BitmapFactory.Options();
            o.inJustDecodeBounds = true;

            BitmapFactory.decodeStream(in, null, o);
            in.close();

            int scale = 1;
            if (o.outHeight > 1024 || o.outWidth > 1024) {
                scale = (int) Math.pow(2, (int) Math.round(Math.log(1024 / (double) Math.max(o.outHeight, o.outWidth)) / Math.log(0.5)));
            }

            BitmapFactory.Options o2 = new BitmapFactory.Options();
            o2.inSampleSize = scale;
            in = context.getContentResolver().openInputStream(uri);
            Bitmap b = BitmapFactory.decodeStream(in, null, o2);
            in.close();

            return b;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

Please can you explain what is problem? How to detect java.lang.OutOfMemoryError exception.

Sunnatilla
  • 51
  • 1
  • 5

0 Answers0