Volley request is done inside a while. It duplicates for no reason ( seemingly ) For example when I suppose to make two requests, volley does it 4 times. Below is my code, some of you could hint the problem in my code ?
while(i<chnumTxt.length()){
final RequestQueue queue;
queue = Volley.newRequestQueue(this);
char letter=chnumTxt.charAt(i);
Log.i("check","counter="+i+" "+"digit="+letter);
String URL = "http://192.168.4.20:80/chnumber?key="+letter;
Log.i("web",URL);
StringRequest request = new StringRequest(Request.Method.GET, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//Log.i("html",response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
queue.add(request);
new CountDownTimer(500, 500) {
public void onFinish() {
// When timer is finished
// Execute your code here
}
public void onTick(long millisUntilFinished) {
}
}.start();
i++;
}
Eventually i found the answer somewhere. Volley will retry links if the link seems slow. So after blocking it, got it right. It is like :
First declare a variable :
static final float DEFAULT_BACKOFF_MULT = 1f;
and after defining the request, do below code :
request.setRetryPolicy(new DefaultRetryPolicy(20 * 1000, 0,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
Related
This answer should be simple but I need help.
I add a url call to Volley and on error response I need to know what the URL was that the error is for, I may have 50 different URL's in a single queue for example so I want to know which one of the 50 returned the error.
Here is my code:
public void upload(String passurl) {
StringRequest stringRequest;
// Request a string response
stringRequest = new StringRequest(Request.Method.GET, passurl,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG,"Send successful");
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//***I want the URL that failed here!
error.printStackTrace();
}
});
stringRequest.setRetryPolicy(new DefaultRetryPolicy(30000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
// Add the request to the queue
stringRequest.setShouldCache(false);
stringRequest.setTag(TAG);
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(this.getApplicationContext());
mRequestQueue.start();
}
mRequestQueue.getCache().clear();
mRequestQueue.add(stringRequest);
}
To expand on #Levon's answer make passurl final for example method(final String passurl)
So I've run into a problem in my code, where I need to get a JSONString from my server with volley. And then I have to parse the String into a JSONObject and then continue doing stuff with that.
My problem here is, that Volley gives the response too late, meaning my string that I want to parse is always empty because its not initialised yet.
RequestFuture<String> future = RequestFuture.newFuture();
StringRequest stringRequest = new StringRequest(Request.Method.GET, searchURLBuilder, future, future);
// new Response.Listener<String>() {
// #Override
// public void onResponse(String response) {
// writeToSharedResponse(response_for_search, response);
// }
// },
// new Response.ErrorListener() {
// #Override
// public void onErrorResponse(VolleyError error) {
// Log.d("Error!!:" + error.getMessage(), "");
// }
// });
requestQueue.add(stringRequest);
String response = "";
try {
response = future.get(60, TimeUnit.SECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (TimeoutException e) {
e.printStackTrace();
}
String responseString = m.getString(response_for_search, new String());
pieceDTOList = getPiecesDTOFromJSON(responseString);
Here is a snippet of my code. As you can see I already tried to make a "future" call to block and wait for the answer, but it just times out every time. The commented out bit, is the part I actually wanted to use from the beginning, but that returns the response to late. Since its asynchronous and accesses the server w/e it wants.
writeToSharedResponse just writes the answer into a sharedPreferences variable.
private SharedPreferences m;
private SharedPreferences.Editor editor;
private RequestQueue requestQueue;
public DbParser(Context c) {
m = PreferenceManager.getDefaultSharedPreferences(c);
editor = m.edit();
requestQueue = Volley.newRequestQueue(c);
}
My Question here is: Is there an easy way I can "wait" for the answer from volley so I can continue to work with the response that I get?
Edit 1:
I now added an interface and changed the code around to this:
getString(new VolleyCallback() {
#Override
public void onSuccess(String result) {
getPiecesDTOFromJSON(result);
}
}, searchURLBuilder);
return globalPieceDTOList;
}
private void getString(final VolleyCallback callback, String searchUrl){
StringRequest stringRequest = new StringRequest(Request.Method.GET, searchUrl,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
callback.onSuccess(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("Error!!:" + error.getMessage(), "");
}
});
requestQueue.add(stringRequest);
}
Since I cant get the values out of my inner classes, I did a nasty hack and created a global list for my DTO's. The problem now is that "return globalPieceDTOList" is always Null. And again - I would need to "wait" for the Volley response.
Volley requests are async, so when you try to return a value, the request is likely not done yet. If you want to return values from a Volley request use callback interfaces.
Example
public void getString(final VolleyCallback callback) {
StringRequest strReq = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// do some things here
callback.onSuccess(<PASS STRING RESULT HERE>);
}
});
}
public interface VolleyCallback{
void onSuccess(String result);
}
Example usage:
public void onResume(){
super.onResume();
getString(new VolleyCallback(){
#Override
public void onSuccess(String result){
//do stuff here with the result from the volley request
}
});
}
I have recently started on Android development platform. I am using Android Studio, and using Volley library for network operation. I have implemented a backend for push notification for iOS and it is working very well, and now I am triggering this php via Volley network operation as follows.
For some reasons it calls that URL multiple times (5 or 6 times), how do I know? because iOS device receives multiple notifications. I am not sure why this happens and how I could solve it?
public void onClick(View v) {
if(v == buttonBuy) {
message = (EditText) findViewById(R.id.offerText);
buy();
}
}
private void buy()
{
StringRequest postRequest = new StringRequest(Request.Method.POST, Config.ASK_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
} catch (Exception e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
}
) {
#Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<>();
params.put("token",token);
params.put("pname",objee.optString("pname"));
params.put("toid",objee.optString("uid"));
params.put("pid",pid);
params.put("message",message.getText().toString().trim());
return params;
}
};
CustomVolleyRequest.getInstance(this).getRequestQueue().add(postRequest);
}
Try to add the following code:
int socketTimeout = 10000; //10 seconds - change to what you want
RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
postRequest.setRetryPolicy(policy);
I am using Volley Network Library in my application.
The Issue is that it is sending data more than once when network connection is slow.
And After I Google this issue, all i can find about this issue is below point:
connection.setChunkedStreamingMode(0);
But I am not able to edit my volley library Hurlkstack classes.
It says:
The jar of this class file belong to container android Private libraries which does not allow modification to source attachments on it entries.
What should i do can some one help me
i have the following code where should i modify
.
private void makeJsonObjectRequest() {
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.POST,
"http://example.com/***.php", obj, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
response.getString("success");
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
AppController.getInstance().addToRequestQueue(jsonObjReq);
}
No need to use connection.setChunkedStreamingMode(0); to avoid volley sending data twice bug. you need to set retry policy for current request :
JsonObjectRequest jsonObjReq = new JsonObjectRequest(...);
jsonObjReq.setRetryPolicy(new DefaultRetryPolicy(
0,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
Use below code after completion of new Response.ErrorListener() method in your volley parsing. Hope its useful for you. I faced same issue and resolved it with the same code.
Code:
jsObjRequest.setRetryPolicy(new DefaultRetryPolicy(
30000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
This will work
RetryPolicy mRetryPolicy = new DefaultRetryPolicy(
0,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
request.setRetryPolicy(mRetryPolicy);
Try this will definitely work.
public <T> void addToRequestQueue(StringRequest req, String tag) {
req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
req.setRetryPolicy(new DefaultRetryPolicy(20 * 1000, 0, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
getRequestQueue().add(req);
}
I solve this problem to use this code. Set getCurrentRetryCount() to return 0 and Use HurlStack for BaseHttpStack.
RequestQueue requestQueue = Volley.newRequestQueue(NavigationActivity.this, new HurlStack());
requestQueue.add(stringRequest).setRetryPolicy(new RetryPolicy() {
#Override
public int getCurrentTimeout() {
return 5000;
}
#Override
public int getCurrentRetryCount() {
return 0; //retry turn off
}
#Override
public void retry(VolleyError error) throws VolleyError {
}
});
Hope this solve the problem.
I want to pass a response outside of my classes (many classes)
public static void userLocation()
{
RequestQueue queue = Volley.newRequestQueue(context);
String url = "http://www.jobdiagnosis.com/iphone/userlocation.php";
StringRequest dr = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>()
{
#Override
public void onResponse(String response) {
// response
//Toast.makeText(context, ""+response, Toast.LENGTH_LONG).show();
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
// error.
// Toast.makeText(getApplicationContext(), "error"+error, Toast.LENGTH_LONG).show();
Log.d("error", ""+error);
}
}
);
queue.add(dr);
}
Please suggest how I can pass a response outside of the class
In volly its difficult to return response outside the class.because request on server run in background and if we return value followed by queue.add(url) then it will return null.So there is no solution till now.Thanks!!