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/