我使用Timer
重复请求。一段时间后我得到OutOfMemoryError
。我扩展Application类以获得单个实例。但我仍然得到错误和应用程序崩溃。清除缓存后它再次起作用。
我每隔几秒就以编程方式清除缓存,但是当我这样做时,我得到NegativeArraySizeException
。我做的单个实例的事情是错的。
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;
}
应用程序类:
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;
}
答案 0 :(得分:1)
也许是因为你反复创建新的String
。请改用StringBuffer
。