Showing posts with label out of memory exception. Show all posts
Showing posts with label out of memory exception. Show all posts

Tuesday, July 5, 2016

Processing Bitmap and Memory Management in Android




Hi, in this Blog post I will explain how to deal with bitmaps in Android and avoid memory leaks and out of memory errors. I will give you some tips on how you can use low memory and can get same results.


First of all let me add some points why your Application can crash due to out of memory error when you are dealing with bitmaps in your Android Application.


1. In Android operating system every application has specific memory limit which can be assigned to it, so that its code can execute in that available memory. it is usually 16MB for most of devices.


And if you are processing larger bitmap say 5MP photo. Memory required for decoding this bitmap is 2592*1936*4 is 19MB (Value 4 is color channel, will explain below). out of memory error, without doing any important, long running task :(


2 . You are loading multiple bitmaps at once for displaying in list view, grid view and view pager.

And you are trying to allocate more space than available heap.


Please note
dalvik do not merge free memory blocks automatically. for example you have 5MB free space and you need 2MB but you still get out of memory error because there is memory leak. you do not have 2MB available space in a single block.


3. There could be memory leak if Object cannot be garbage collected. Why an object cannot be garbage collected. I will explain below,


Now here are tips which you can follow and can avoid out of memory exception in your Android Application.
1. Always use Activity context instead of Application context. because Application context cannot be garbage collected. And release resources as your activity finishes. (life cycle of object should be
same as of activity).

2 . When Activity finishes. Check HEAP DUMP (memory analysis tool in Android studio).

If there are objects in HEAP DUMP from finished activity there is memory leak. review your
code and identify what is causing memory leak.

3. Always use inSampleSize

Now what is inSampleSize ?
with the help of inSampleSize you are actually telling the decoder not to grab every pixel in memory, instead sub sample image.
This will cause less number of pixels to be loaded in memory than the original image. you can tell decoder to grab every 4th pixel or every second pixel from original image.
if inSampleSize is 4. decoder will return an Image that is 1/16 the number of pixels in original image.

so how much memory you have saved ? calculate :)

4.  Read Bitmap Dimensions before loading into memory.

     How reading bitmap dimensions before loading image into memory can help you avoid out of       
     memory error ? Let's Learn

     use inJustBounds = true

here is technique with the help of which you can get image dimension beore loading it in memory

BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.id.myimage, options);
int imageHeight = options.outHeight;
int imageWidth = options.outWidth;
String imageType = options.outMimeType;

Above code snippet will not give us any image/bitmap.  it will return null for bitmap Object.
but it will definitely return width and height of that image. which is R.id.myimage.

Now you have width and height of Image. you can scale up or scale down image based on these factors:

- ImageView size which will be used to display Image.
- Available amount of memory. you can check available amount of memory using ActivityManager    and getMemoryClass. 
- Screen size and density of device.

5. Use appropriate Bitmap Configuration

   Bitmap configurations is color space/color depth of an Image. Default bitmap Configuration in     Android is RGB_8888 which is 4 bytes per pixel.

If you use RGB_565 color channel which use 2 Bytes per pixel. half the memory allocation for same resolution :)


6. Use inBitmap property for recycling purpose.

7. Do not make static Drawable Object as it cannot be garbage collected.

8. Request large heap in <application> in manifest file.

9. Use multiple processes if you are doing lot of image processing(memory intensive task) or use NDK (Native Development    using c, c++)


Author:
Hammad Tariq
Android Developer

Wednesday, December 23, 2015

Android Volley Out of memory exception fixed using clear app cache dynamically


Hi, I used Volley in one of my project and at a time our API data changed from smaller to larger one.
and our Application started crashing and giving out of memory error. And when we clear App data and start Application again it worked fine.

After looking at certain links like
volley out of memory error
volley out of memory error 2

these links did'nt helped me but after noticing that when I clear App data app works fine. So here is solution which is working perfect for me and my App do not crash.

JSONObject mainObject = null;
INetworkOperationListner getJSONListener;

INetworkOperationListner will send data to Activity which called below doInBackGround method.
please note this is not AsyncTask doInBackground, this is my custom doInBackground. Volley donot need AsyncTask.

When request is completed and onResponse method is called I am callling deleteCache(context) method. which will clear cache after every call and no Out of memory error will occur.

public JSONObject doInBackground(HashMap<String,String> params, final String url) {
        RequestQueue mRequestQueue;
           JsonObjectRequest req = new JsonObjectRequest(url, new JSONObject(params),
                new com.android.volley.Response.Listener<JSONObject>() {
                    @Override                    public void onResponse(JSONObject response) {
                        mainObject = response;
                        try {
                            deleteCache(context);
                            getJSONListener.onRemoteCallComplete(response.toString());

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new com.android.volley.Response.ErrorListener() {
            @Override            public void onErrorResponse(VolleyError error) {
            }
        }
        )
        {
       @Override            public Map<String, String> getHeaders() throws AuthFailureError {
                HashMap<String, String> headers = new HashMap<String, String>();
                headers.put("Username", Constants.Username);
                headers.put("Password", Constants.Password);
                return headers;
            }
        };
        int socketTimeout = 15000;
        RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_TIMEOUT_MS, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
        req.setRetryPolicy(policy);
        //mRequestQueue.add(req);        Volley.newRequestQueue(context).add(req);

        return mainObject;
    }


How to delete Android Application cache programatically deleteCache(Context) will be called from onResponse.

public static void deleteCache(Context context) {
    try {
        File dir = context.getCacheDir();
        deleteDir(dir);
    } catch (Exception e) {}
}

public static boolean deleteDir(File dir) {
    if (dir != null && dir.isDirectory()) {
        String[] children = dir.list();
        for (int i = 0; i < children.length; i++) {
            boolean success = deleteDir(new File(dir, children[i]));
            if (!success) {
                return false;
            }
        }
        return dir.delete();
    }
    else if(dir!= null && dir.isFile())
        return dir.delete();
    else {
        return false;
    }
}

Acknowledgment: I got above delete app cache from stack overflow.
Use above code and enjoy your app will never crash due to volley out of memory error. :)




Kotlin Android MVP Dagger 2 Retrofit Tutorial

http://developine.com/building-android-mvp-app-in-kotlin-using-dagger-retrofit/