I make repeated requests using a Timer
. I get OutOfMemoryError
after a while. I extend Application class to get a single instance. But I still get the error and app crashes. It works again after I clear the cache.
I programmatically clear the cache every few seconds, but when I do that I get NegativeArraySizeException
. Am I doing the single instance thing wrong.
public ArrayList getCo_ordinates(String deviceId) {
String URL_CO_ORDINATES = "http://192.168.1.42:8080/image/getDevicePosition?deviceId=" + deviceId;
myApplication.getRequestQueue().start();
final JsonArrayRequest request = new JsonArrayRequest(URL_CO_ORDINATES, new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
try {
for (int i = 0; i < response.length(); i++) {
X = response.getJSONObject(i).getString("xCoordinate");
Y = response.getJSONObject(i).getString("yCoodinate");
System.out.println("xCoordinate" + X);
System.out.println("yCoodinate" + Y);
if(isCoordinateDifferent()) {
addTap(Integer.parseInt(X), Integer.parseInt(Y));
}else {
}
updateNewCoordinates(Integer.parseInt(X),Integer.parseInt(Y));
}
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(context, "" + e, Toast.LENGTH_SHORT).show();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError volleyError) {
Toast.makeText(getApplicationContext(), "Could Not connect to server", Toast.LENGTH_LONG).show();
}
})
{
@Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
String deviceID = Build.SERIAL;
params.put("Content-Type", "application/json; charset=utf-8");
return params;
}
};
myApplication.addToRequestQueue(request);
return null;
}
The application class:
public class MyApplication extends Application {
private int cacheClearCount=0;
private static MyApplication myApplication;
private int installCount = 0;
private RequestQueue requestQueue;
@Override
public void onCreate() {
super.onCreate();
myApplication = this;
requestQueue = Volley.newRequestQueue(getApplicationContext());
}
public MyApplication(){
}
public int getCacheClearCount() {
return cacheClearCount;
}
public RequestQueue getRequestQueue() {
return requestQueue;
}
public <T> void addToRequestQueue(Request<T> request, String tag) {
getRequestQueue().add(request);
}
public <T> void addToRequestQueue(Request<T> request) {
getRequestQueue().add(request);
}
public void cancelPendingRequest(Object tag) {
getRequestQueue().cancelAll(tag);
}
public void setCacheClearCount(int cacheClearCount) {
this.cacheClearCount = cacheClearCount;
}
public static MyApplication getInstance() {
return myApplication;
}