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();
}
Related
i want to cancel volley request if there is no response in specific time
StringRequest stringRequest = new StringRequest(Request.Method.POST, test_check_url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("resultarray");
JSONObject jsonObject1 = jsonArray.getJSONObject(0);
Calendar calendar = Calendar.getInstance();
} catch (Exception e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> map = new HashMap<>();
map.put("test_id","");
map.put("chap_id","");]
map.put("type","check_test");
return map;
}
};
stringRequest.setTag(TAG);
MySingleton.getInstance(getContext()).addToRequestQueue(stringRequest);
i tried doing this:
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
if (MySingleton.getInstance(getContext()).getRequestQueue() != null) {
MySingleton.getInstance(getContext()).getRequestQueue().cancelAll(TAG);
Toast.makeText(getContext(), "Request failed"+TAG, Toast.LENGTH_SHORT).show();
}
}
}, 10000);
i want to show a toast and cancel my request if there no response in 10 seconds
how can i do this?
Thank you in advance
You can set timeout to your request.
after that particular timeout your request will be failed and you can catch that exception inside your onErrorResponse(VolleyError error) and here you can show Toast
in your case here is the example
stringRequest.setRetryPolicy(new DefaultRetryPolicy(MY_TIMEOUT_MS,DefaultRetryPolicy.DEFAULT_MAX_RETRIES,DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
MySingleton.getInstance(getContext()).addToRequestQueue(stringRequest);
set MY_TIMEOUT_MS to 10000 milliseconds and DEFAULT_MAX_RETRIES to 0
now after 10 seconds the request will be failed and inside your ErrorResponse you can catch it like this and show Toast
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
if (error instanceof TimeoutError || error instanceof NoConnectionError||error instanceof NetworkError) {
Toast.makeText(context,context.getString(R.string.error_network_timeout),Toast.LENGTH_LONG).show();
}
}
I want to post an int to an https address and pass 3 JSON objects to text views and I can't get JSON results. I've tried to use methods in onResponse but it's not working. How can I POST an integer and parse some JSON objects to text views? I'm a beginner in Android developing and I don't know how to resolve this problem.
What's the problem? please help
if(isNetworkAvailable()){
RequestQueue queue = Volley.newRequestQueue(this);
String url = "https://example.com/api";
StringRequest postRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<JSONObject>()
{
#Override
public void onResponse(JSONObject response) {
try {
Log.d("Response", response);
} catch (JSONException e) {
e.printStackTrace();
alertUserAboutError();
}
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
// error
mStoreName.setText("Error");
}
}
) {
#Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<String, String>();
params.put("category_id", "28");
return params;
}
};
queue.add(postRequest);
}
Toast.makeText(this, "Network is unavailable!", Toast.LENGTH_LONG).show(); }
private void updateDisplay() {
mStoreName.setText(mStoreDetails.getStoreName());
mInstagram.setText(mStoreDetails.getInstagram());
mTelegram.setText(mStoreDetails.getTelegram());
}
private StoreDetails getStoreDetails(String jsonData) throws JSONException {
JSONObject JSONRequest = new JSONObject(jsonData);
StoreDetails storeDetails = new StoreDetails();
storeDetails.setStoreName(JSONRequest.getString("store_name"));
storeDetails.setInstagram(JSONRequest.getString("instagram"));
storeDetails.setTelegram(JSONRequest.getString("telegram"));
return storeDetails;
}
private boolean isNetworkAvailable() {
ConnectivityManager manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = manager.getActiveNetworkInfo();
boolean isAvailable = false;
if (networkInfo != null && networkInfo.isConnected()) {
isAvailable = true;
}
return isAvailable;
}
private void alertUserAboutError() {
AlertDialogFragment dialog = new AlertDialogFragment();
dialog.show(getFragmentManager(), "error_dialog");
}
This works for me. Use an stringrequest to put the post data to the request. After onResponse was called I create an JSON-Object from the string:
public void doServerRequest(final Context context, final String url, final Map<String,String> postParameters, final HashMap<String,String> getParameters, final OnFinishTaskListener<String, JSONObject> listener){
Log.d(TAG,"Start new server request (" + url + ")");
StringRequest request = new StringRequest(Request.Method.POST, addParametersToUrl(url, getParameters), new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, response);
try {
JSONObject json = new JSONObject(response);
if (json.getInt(CODE_TAG) == 0){
listener.getResult(SUCCESS_TAG, json);
} else {
listener.getResult(ERROR_TAG, null);
}
} catch (Exception e){
e.printStackTrace();
listener.getResult(ERROR_TAG, null);
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
listener.getResult(ERROR_TAG, null);
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
if(postParameters == null){
return new HashMap<String, String>();
}
return postParameters;
}
};
requestQueue.add(request);
}
This adds the get-Paramters to the URL (if exist):
private String addParametersToUrl(String url, HashMap<String,String> getParameters){
if(getParameters == null || getParameters.size() == 0){
return url;
}
Log.d(TAG,"Preparing URL: "+url);
StringBuilder stringBuilder = new StringBuilder(url);
stringBuilder.append("?");
int i = 0;
for (String key : getParameters.keySet()) {
if(i>0) stringBuilder.append("&");
stringBuilder.append(key).append("=").append(getParameters.get(key));
i++;
}
url = stringBuilder.toString();
Log.d(TAG,"Prepared URL: "+url);
return url;
}
I use this listener interface:
public interface OnFinishTaskListener<S,J> {
public void getResult(S string, J json);
}
I'm trying to figure out reason doInBackground() cannot save field values. Even return value changes back to initial after return statement. I have initialed AsyncTask onCreate() in the main class. Everything works fine until onPostExecute().
Thanks in advance
private class UserRegisterTask extends AsyncTask<Void, Void, Boolean> {
JSONObject jsonObj;
String uuid;
String ok;
String errorMessage;
Boolean noErrors = false;
public UserRegisterTask() {
}
Here is doInBack...
#Override
protected Boolean doInBackground(Void... params) {
final String url = "https://webaddress/register.php";
final Context context = getContext();
// 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) {
try {
jsonObj = new JSONObject(response);
String error = jsonObj.getString("error");
if (error.equals("false")) {
uuid = jsonObj.getString("unique_id");
noErrors = true;
Log.e("####ยค%", String.valueOf(noErrors.booleanValue()));
mEmail = jsonObj.getString("email");
ok = jsonObj.getString("ok");
} else {
errorMessage = jsonObj.getString("error_msg");
Log.d("XXXXXXXXXXXXX", errorMessage);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//mTextView.setText("That didn't work!");
Log.e("ERROR", error.getMessage());
error.printStackTrace();
}
})
{
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("password", mpassword);
params.put("email", mEmail);
return params;
}
};
AppController.getInstance().addToRequestQueue(stringRequest);
return noErrors;
}
And here is onPostExecute()
#Override
protected void onPostExecute(Boolean success) {
urt = null;
if (success.booleanValue()) {
Toast toast = Toast.makeText(getApplicationContext(), ok, Toast.LENGTH_LONG);
toast.show();
new Thread(new Runnable() {
public void run() {
new SendEmail(mEmail, sb.toString(), uuid);
}
}).start();
Intent intent = new Intent(RegisterActivity.this, LoginActivity.class);
intent.putExtra("email", mEmail);
startActivity(intent);
// finish();
} else {
Toast toast = Toast.makeText(getApplicationContext(), errorMessage, Toast.LENGTH_SHORT);
toast.show();
Intent intent = new Intent(RegisterActivity.this, LoginActivity.class);
startActivity(intent);
}
}
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
I try to execute a new volley request in the current volley request, but when the new request is called it don't step into the onrespond method.
The new request should be executed before the first ends. (Last in, first out)
How can I execute the new request succesfully ?
private void makeJsonObjectRequest() {
ac = new AppController();
final JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.GET,
url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("test", response.toString());
try {
// Parsing json object response
// response will be a json object
JSONArray name = response.getJSONArray("data");
for (int i = 0; i < name.length(); i++) {
JSONObject post = (JSONObject) name.getJSONObject(i);
try {
objectid = post.getString("object_id");
newRequest(objectid);
}
catch (Exception e) {
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("test", "Error: " + error.getMessage());
}
});
// Adding request to request queue
ac.getInstance().addToRequestQueue(jsonObjReq);
}
Try it Work 100%
public class Utility {
String result = "";
String tag_string_req = "string_raq";
private Activity activity;
Context context;
private LinearLayout mLinear;
private ProgressDialog pDialog;
public Utility(Context context) {
this.context = context;
}
public String getString(String url, final VolleyCallback callback) {
showpDialog();
StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
result = response;
hideDialog();
callback.onSuccess(response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
callback.onRequestError(error);
hideDialog();
/*LayoutInflater inflater = ((Activity) context).getLayoutInflater();
View layout = inflater.inflate(R.layout.custom_toast, null);
((Activity) context).setContentView(layout);*/
}
});
VolleySingleton.getInstance().addToRequestQueue(stringRequest, tag_string_req);
stringRequest.setRetryPolicy(
new DefaultRetryPolicy(1 * 1000, 1, 1.0f));
return result;
}
public interface VolleyCallback {
void onSuccess(String result);
void onRequestError(VolleyError errorMessage);
//void onJsonInvoke(String url, final VolleyCallback callback);
}
public boolean isOnline() {
Runtime runtime = Runtime.getRuntime();
try {
Process ipProcess = runtime.exec("/system/bin/ping -c 1 8.8.8.8");
int exitValue = ipProcess.waitFor();
return (exitValue == 0);
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
return false;
}
private void showpDialog() {
onProgress();
if (!pDialog.isShowing())
pDialog.show();
}
private void hideDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
public void onProgress() {
pDialog = new ProgressDialog(context);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
}
}
Call Fragment
Utility utility = new Utility(getContext());
utility.getString(urls, new Utility.VolleyCallback() {
#Override
public void onSuccess(String result) {
try {
JSONObject toplinks = new JSONObject(result);
JSONObject data = toplinks.getJSONObject("toplinks");
M.i("============LS", "" + data);
} catch (JSONException e) {
e.printStackTrace();
}
finally {
}
}
#Override
public void onRequestError(VolleyError errorMessage) {
errorJson.setVisibility(View.VISIBLE);
String msg = VolleyException.getErrorMessageFromVolleyError(errorMessage);
errorJson.setText(msg);
}
});
all this about
Request Prioritization
Networking calls is real time operation so let consider we have multi request like in your case , Volley processes the requests from higher priorities to lower priorities , in first-in-first-out order.
So all you need change priority (set Priority.HIGH) to request you want process first.
here is a piece of code
public class CustomPriorityRequest extends JsonObjectRequest {
// default value
Priority mPriority = Priority.HIGH;
public CustomPriorityRequest(int method, String url, JSONObject jsonRequest, Response.Listener<JSONObject> listener, Response.ErrorListener errorListener) {
super(method, url, jsonRequest, listener, errorListener);
}
public CustomPriorityRequest(String url, JSONObject jsonRequest, Response.Listener<JSONObject> listener, Response.ErrorListener errorListener) {
super(url, jsonRequest, listener, errorListener);
}
#Override
public Priority getPriority() {
return mPriority;
}
public void setPriority(Priority p){
mPriority = p;
}
}
As others mentioned one way is to put a high priority on the request.
Another option as it seems you have the first request depending on the inner one wrapped in the try-catch block which seems to me you want to achieve a synchronous/blocking behavior for this specific case. then you can use RequestFuture :
RequestFuture<String> future = RequestFuture.newFuture();
StringRequest request = newRequest(objectid, future);
requestQueue.add(request);
String result = future.get();