I'm updating my API every 2seconds,
but I am receiving this error and my application closes.
FATAL EXCEPTION: main
Process: com.application.toweeloasep, PID: 6681
java.lang.OutOfMemoryError: Could not allocate JNI Env
at java.lang.Thread.nativeCreate(Native Method)
at java.lang.Thread.start(Thread.java:730)
at com.android.volley.RequestQueue.start(RequestQueue.java:145)
at com.android.volley.toolbox.Volley.newRequestQueue(Volley.java:66)
at com.android.volley.toolbox.Volley.newRequestQueue(Volley.java:78)
at com.application.toweeloasep.fragments.Jobs$5$1.run(Jobs.java:260)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
After about a minute, it starts to crash and receives that error.
Am I overdoing things with Volley?
private void setRepeatingAsyncTask() {
final Handler handler = new Handler();
Timer timer = new Timer();
TimerTask task = new TimerTask() {
#Override
public void run() {
handler.post(new Runnable() {
public void run() {
try {
if (checkRequests) {
RequestQueue mRequestQueue = Volley.newRequestQueue(getActivity());
StringRequest mStringRequest = new StringRequest(Request.Method.POST, "http://api.000.com/booking/track", new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.e("RESPONSE:TRACK", response);
try {
JSONObject json = new JSONObject(response);
String mStatus = json.getString("status");
if (mStatus.equalsIgnoreCase("0")) {
Log.e("STATUS", mStatus);
} else if (mStatus.equalsIgnoreCase("1")) {
JSONArray infos = json.getJSONArray("data");
booking_id = infos.getJSONObject(0).getString("id");
user_address_location = infos.getJSONObject(0).getString("user_address_location");
mTxtBatteryInfo.setText(infos.getJSONObject(0).getJSONObject("battery").getString("model"));
mTxtUserLocation.setText(user_address_location);
checkRequests = false;
mJobsHome.setVisibility(View.GONE);
mJobRequest.setVisibility(View.VISIBLE);
if (!onTick) {
mCountDownTimer.start();
onTick = true;
}
}
} catch (Exception e) {
Log.e("ERR", e.toString());
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("ERR", error.toString());
}
});
mRequestQueue.add(mStringRequest);
} else {
RequestQueue requestPlaceInfo = Volley.newRequestQueue(getActivity());
StringRequest request2 = new StringRequest(Request.Method.POST, "http://api.000.com/booking/track", new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.e("RESPONSE", response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(), error.toString(), Toast.LENGTH_SHORT).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("booking_id", booking_id);
params.put("rider_long", String.valueOf(lng));
params.put("rider_lat", String.valueOf(lat));
return params;
}
};
requestPlaceInfo.add(request2);
}
} catch (Exception e) {
// error, do something
}
}
});
}
};
timer.schedule(task, 0, 2000); // interval of one minute
}
OutOfMemoryError ... at com.android.volley.toolbox.Volley.newRequestQueue
Why do you need to create a new RequestQueue or StringRequest every two seconds?
Try making only one of each.
private final Response.ErrorListener errorListener = new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("ERR", String.valueOf(error));
}
};
private void setRepeatingVolleyTask() {
final RequestQueue mRequestQueue = Volley.newRequestQueue(getActivity());
final StringRequest trackRequest = new StringRequest(Request.Method.POST, "http://api.toweelo.com/booking/track", new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("RESPONSE:TRACK", response);
try {
JSONObject json = new JSONObject(response);
String mStatus = json.getString("status");
if (mStatus.equalsIgnoreCase("0")) {
Log.d("STATUS", mStatus);
} else if (mStatus.equalsIgnoreCase("1")) {
JSONArray infos = json.getJSONArray("data");
booking_id = infos.getJSONObject(0).getString("id");
user_address_location = infos.getJSONObject(0).getString("user_address_location");
mTxtBatteryInfo.setText(infos.getJSONObject(0).getJSONObject("battery").getString("model"));
mTxtUserLocation.setText(user_address_location);
checkRequests = false;
mJobsHome.setVisibility(View.GONE);
mJobRequest.setVisibility(View.VISIBLE);
if (!onTick) {
mCountDownTimer.start();
onTick = true;
}
}
} catch (Exception e) {
Log.e("ERR", e.toString());
}
}
}, errorListener );
final StringRequest trackRequest2 = new StringRequest(Request.Method.POST, "http://api.toweelo.com/booking/track", new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("RESPONSE", response);
}
}, errorListener) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("booking_id", booking_id);
params.put("rider_long", String.valueOf(lng));
params.put("rider_lat", String.valueOf(lat));
return params;
}
};
Timer timer = new Timer();
TimerTask task = new TimerTask() {
#Override
public void run() {
handler.post(new Runnable() {
public void run() {
// What are you trying to catch here??
try {
if (checkRequests) {
mRequestQueue.add(trackRequest);
} else {
mRequestQueue.add(trackRequest2);
} catch ( ... ) {
....
}
Note: You can use JsonObjectRequest instead of parsing JSON from a StringRequest
Related
I am developing an app in which i find the origin and destination of a car and send it to a server.
I know how to use volley to send an string however i am finding it hard to send data in JSON format.
Part of the code is given below:
b
tnFindPath.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RequestQueue queue = Volley.newRequestQueue(MapsActivity.this);
String url = "http://192.168.43.162:8080/";
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
//adding parameters to the request
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("origin", etOrigin.getText().toString());
params.put("destination", etDestination.getText().toString());
return params;
}
};
// Add the request to the RequestQueue.
queue.add(stringRequest);
try this
final String httpUrl = //your url
try {
JSONArray parameters = new JSONArray();
JSONObject jsonObject = new JSONObject();
jsonObject.put(Key,value);
jsonObject.put(Key,value);
parameters.put(jsonObject);
Log.i(TAG,parameters.toString());
JsonArrayRequest arrayRequest = new JsonArrayRequest(Request.Method.POST, httpUrl, parametersForPhp,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG,response.toString());
try {
//your code
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
RequestQueueSingleton.getInstance(getApplicationContext()).addToRequestQueue(arrayRequest);
}catch (Exception e){
e.printStackTrace();
}
}
I want to update data in Textview text with 5 second interval. The data should comes for server. I call the "handler" with 15000 ms interval.
Problem is few times app crass due to call handler. Please tell me is there any other process to update data with time interval. I am sending the following code which I have used.
final Handler handler = new Handler();
Timer timer = new Timer();
TimerTask doAsynchronousTask = new TimerTask() {
#Override
public void run() {
handler.post(new Runnable() {
public void run() {
try {
if(dataFromLogin.trim().equals("yes"))
{
checkUrlToFetchData(personLoginName);
}
else
{
checkUrlForExtraVideo(latestVideoID);
checkUrlToFetchDataCreaterLogin(personLoginName);
}
} catch (Exception e) {
// TODO Auto-generated catch block
}
}
});
}
};
timer.schedule(doAsynchronousTask, 0, 15000);
=============================
void checkUrlToFetchData(final String useridt)
{
RequestQueue queue = Volley.newRequestQueue(AllItemScreen.this);
String url = "http://liveapp.99emailmarketing.com/notifications/index";
StringRequest stringRequest = new StringRequest(com.android.volley.Request.Method.POST, url,
new com.android.volley.Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.v( "response:",response);
try {
JSONObject jsonObj = new JSONObject(response);
boolean success = jsonObj.getBoolean("success");
if(success == true)
{
JSONArray notifications = jsonObj.getJSONArray("notifications");
if(notifications.length()>0)
{
JSONObject jo= notifications.getJSONObject(0);
createNotification(jo.getString("message"));
}
}
else
{
String error = jsonObj.getString("error");
Toast.makeText(AllItemScreen.this, error, Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
Log.v( "try:",e.toString());
}
}
}, new com.android.volley.Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(AllItemScreen.this, "That didn't work!", Toast.LENGTH_SHORT).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("user_id",userIdfromLogin);
return params;
}
};
queue.add(stringRequest);
}
void checkUrlToFetchDataCreaterLogin(final String useridt)
{
//Toast.makeText(this, "Validation Successfull", Toast.LENGTH_LONG).show();
RequestQueue queue = Volley.newRequestQueue(AllItemScreen.this);
String url = "http://liveapp.99emailmarketing.com/LiveNotifications/index";
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(com.android.volley.Request.Method.POST, url,
new com.android.volley.Response.Listener<String>() {
#Override
public void onResponse(String response) {
// Display the response string.
//progressDialog.dismiss();
//Toast.makeText(AllItemScreen.this, "response:"+response, Toast.LENGTH_SHORT).show();
Log.v( "response:",response);
try {
//Log.v( "try:","1");
JSONObject jsonObj = new JSONObject(response);
boolean success = jsonObj.getBoolean("success");
String profileimages="",profileimages1="",profileimages2="",profileimages3="",profileimages4="",profileimages5="";
if(success == true)
{
JSONArray notifications = jsonObj.getJSONArray("LiveNotifications");
if(notifications.length()>0)
{
JSONObject jo= notifications.getJSONObject(0);
createNotification(jo.getString("message"));
}
}
else
{
String error = jsonObj.getString("error");
Toast.makeText(AllItemScreen.this, error, Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
Log.v( "try:",e.toString());
}
}
}, new com.android.volley.Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//progressDialog.dismiss();
Toast.makeText(AllItemScreen.this, "That didn't work!", Toast.LENGTH_SHORT).show();
}
}) {
//adding parameters to the request
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("user_id",userIdfromLogin);
return params;
}
};
// Add the request to the RequestQueue.
queue.add(stringRequest);
}
void checkUrlForExtraVideo(final String checkUrlForExtraVideo)
{
RequestQueue queue = Volley.newRequestQueue(AllItemScreen.this);
String url = "http://liveapp.99emailmarketing.com/user-videos/newvideo";
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(com.android.volley.Request.Method.POST, url,
new com.android.volley.Response.Listener<String>() {
#Override
public void onResponse(String response) {
// Display the response string.
//progressDialog.dismiss();
//Toast.makeText(AllItemScreen.this, "response:"+response, Toast.LENGTH_SHORT).show();
Log.v( "response:",response);
try {
//Log.v( "try:","1");
JSONObject jsonObj = new JSONObject(response);
boolean success = jsonObj.getBoolean("success");
if(success == true)
{
int newVideo = jsonObj.getInt("newVideo");
if(newVideo>0)
{
getResourceUriRecyclerViewtruenew(swipeRefreshLayout);
}
}
else
{
String error = jsonObj.getString("error");
Toast.makeText(AllItemScreen.this, error, Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
Log.v( "try:",e.toString());
}
}
}, new com.android.volley.Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//progressDialog.dismiss();
Toast.makeText(AllItemScreen.this, "That didn't work!", Toast.LENGTH_SHORT).show();
}
}) {
//adding parameters to the request
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("video_id",latestVideoID);
return params;
}
};
// Add the request to the RequestQueue.
queue.add(stringRequest);
}
If you want to do some task for every 5 seconds , You can use
Handler handler = new Handler();
new Runnable()
{
#Override
public void run() {
//do your task
handler.postDelayed(this, 5000);
}
}.run();
You can try this for the 5-second timer
private Handler mCountdownHandler;
private final static int INTERVAL = 5 * 1000;
private Runnable mTimer = new Runnable() {
#Override
public void run() {
// Do something
...
...
// Reschedule the timer to execute after 5 seconds
mCountdownHandler.postDelayed(this, INTERVAL);
}
};
private void startTimer() {
stopTimer();
mCountdownHandler = new Handler(getMainLooper());
mCountdownHandler.post(mTimer);
}
private void stopTimer() {
if (mCountdownHandler != null) {
mCountdownHandler.removeCallbacks(mTimer);
mCountdownHandler = null;
}
}
Don't forget to free the handler when you destroy the activity
#Override
protected void onDestroy() {
super.onDestroy();
stopTimer();
}
I am trying to parse Json it will show error
final StringRequest request = new StringRequest(Request.Method.GET, URL_DATA, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// Log.d(TAG, response);
try {
JSONObject jobj = new JSONObject(response);
Log.d(TAG, jobj.toString());
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue reQueue = Volley.newRequestQueue(this);
reQueue.add(request);
}
Here is my api
http://159.65.89.76/userApi/categories
I am sending server request to handle response and error i have implemented interface. I just want to know how to handle if "mResultCallBack ==null" without editing condition if(mResultCallBack!=null). code are as follow:-
public Context mContext;
private IResult mResultCallBack;
public CServerRequest(IResult mResultCallBack, Context context) {
this.mContext = context;
this.mResultCallBack = mResultCallBack;
}
public void postWalletRequest(final String requestType, String url, JSONObject jsonObject) {
try {
RequestQueue queue = Volley.newRequestQueue(mContext);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(url, jsonObject, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
mResultCallBack.notifySuccess(requestType, response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
mResultCallBack.notifyError(requestType, error);
}
});
jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(10000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
queue.add(jsonObjectRequest);
} catch (Exception e) {
e.printStackTrace();
}
}
}
and code for interface
public void notifySuccess(String requestType,JSONObject response);
public void notifyError(String requestType,VolleyError error);
AsyncTask.execute(new Runnable() {
#Override
public void run() {
if (loginSessionManager.isLogin()){
cServerRequest = new CServerRequest(mResultcallBack,mContext);
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject();
jsonObject.put(CRequestKey.AGENT_CODE, m_szMobileNumber.trim());// sending mobile no.(static right know becuse of ser side data on other is null
jsonObject.put(CRequestKey.PIN, m_szEncryptedPassword.trim());// same here as said above
Log.e(TAG,"Request::"+jsonObject.toString());
} catch (JSONException e) {
e.printStackTrace();
}
final String s_szWalletURL = CAPIStorage.IREWARDS_URL + CAPIStorage.WALLET_BALANCE_URL;
cServerRequest.postWalletRequest("POST",s_szWalletURL,jsonObject);
}else {
Log.e(TAG,"Not loggedin");
}
}
});
public Context mContext;
private IResult mResultCallBack;
public CServerRequest(IResult mResultCallBack, Context context) {
this.mContext = context;
this.mResultCallBack = mResultCallBack;
}
public void postWalletRequest(final String requestType, String url, JSONObject jsonObject) {
try {
if(jsonObject.getJSONArray.length() == 0) {
System.out.println("JSONArray is null");
}
else{
System.out.println("JSONArray is not null");
//parse your string here
RequestQueue queue = Volley.newRequestQueue(mContext);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(url, jsonObject, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
mResultCallBack.notifySuccess(requestType, response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
mResultCallBack.notifyError(requestType, error);
}
});
jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(10000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
queue.add(jsonObjectRequest);
}
} catch (Exception e) {
e.printStackTrace();
}
}
When I call getData.It seems that it is hard to get the result out from the onResponse. I know it cannot work in this current way. Could anyone help me to settle this problem?
getData()
private void getData(){
//Creating a string request
StringRequest stringRequest = new StringRequest(SPINNER_URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// Log.d("Country_name","hi");
JSONObject j = null;
try {
//Parsing the fetched Json String to JSON Object
j = new JSONObject(response);
//Storing the Array of JSON String to our JSON Array
result = j.getJSONArray(JSON_ARRAY);
Log.v("xxxxx",result.toString());
String mysh=result.toString().substring(1, result.toString().length()-1);
JSONArray jsonArray = new JSONArray(mysh);
//Calling method getCountry to get the country from the JSON Array
getCountry(jsonArray);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
//Creating a request queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue.add(stringRequest);
}
Try this i think it should work
private void getData(){
//Creating a string request
StringRequest stringRequest = new StringRequest(SPINNER_URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray jsonArray = new JSONArray(response);
getCountry(jsonArray);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
Try that, this will help.
private void getData() {
String tag_string_req = "req_name";
spotsDialog.show();
StringRequest strReq = new StringRequest(Method.POST,
YOUR URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Response: " + response.toString());
try {
JSONObject object = new JSONObject(response);
JSONArray array = object.getJSONArray("YOUR ARRAY NAME");
for (int i=0;i<array.length();i++){
String result = array.getString(i).toString();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Error: " + error.getMessage());
}
});
strReq.setRetryPolicy(new RetryPolicy() {
#Override
public void retry(VolleyError arg0) throws VolleyError {
}
#Override
public int getCurrentTimeout() {
return 0;
}
#Override
public int getCurrentRetryCount() {
return 0;
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue.add(stringRequest);
}
Happy To Help.