How to detect 204 No Content from Android Volley Request - android

When i request to my api api returns 204 - No Content. But volley does not recognise that and give TimeOutError.
How can i handle this ?

When you setup a new volley request :
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// act upon a valid response
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// Handle error
}
});
Notice that you pass a Response.ErrorListener. When error occurs, such as for instance 204, the onErrorResponse(VolleyError) callback is called with the VolleyError instance - error with appropriate information about the error passed to it.
So in this callback you should inspect for the error and take appropriate action.
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if(error instanceof TimeoutError){
// Take action when timeout happens
}
}
}
NOTE : When timeout happens, the VolleyError instance is in fact an instance of TimeoutError a subclass of VolleyError. Hence we check if the error caused is timeout using instanceof
The list of VolleyError sub classes are available here : http://afzaln.com/volley/com/android/volley/VolleyError.html
The example given is for StringRequest type but the technique is the same for other VolleyObjectRequest types.

Related

Handle a 401 error in Volley's onErrorResponse listener

I am using Volley's JsonObjectRequest to fetch JSON data from a web server. Basically my code looks like this:
JsonObjectRequest jsonRequest = new JsonObjectRequest("https://www.example.com", null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
...
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if (error.networkResponse.statusCode == 401) {
// Show toast message saying "Access unauthorized"
} else {
// show toast message saying "Could not fetch"
}
}
});
If the request fails with a 401 error, the "Access unauthorized" toast message is shown as expected. However, if the request fails for some reason such as no internet, the app crashes and throws a NullPointerException because networkResponse does not exist in error.
How do I properly handle both causes of failure?
You can handle this in either of this below ways,
Handle the lost internet signal in your app and navigate to a different page (search for how to handle no internet, lot of articles available)
Surround JsonObjectRequest call in try catch and handle the exception on your own

Android Volley onResponse not getting Called in Certain Activity

I am making Volley GET Requests which will work until I get to a specific activity and then it stops calling the onResponse in the Response.Listener. Here is my Volley Request method:
public static void stringReqGet(String url, final VolleyCallback callback){
StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
System.out.println("In VolleyRequest onResponse(): " + response);
callback.onSuccess(response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("Error" ,error.getMessage());
}
});
System.out.println("Adding request to queue: " + stringRequest.toString());
Utilities.getInstance().addToRequestQueue(stringRequest);
}
Here's how I'm making the request in the activity in question:
CourseUtil.loadCourse(courseID, new VolleyCallback() {
#Override
public void onSuccess(String response) {
System.out.println("JSON Success");
courseJSON = response;
}
});
and in CourseUtil class:
public static void loadCourse(int courseID, VolleyCallback callback){
VolleyRequest.stringReqGet(Const.URL_COURSE + courseID,callback);
}
I'm getting no Volley errors just seemingly no response. Here are my (truncated) logs:
I/System.out: Adding request to queue: [ ] http://server/courses/267267267 0xebb503b0 NORMAL null
I/System.out: In VolleyRequest onResponse(): *Correct Response Object*
.
.
.
I/System.out: 267267267 <-- Same course ID used in first request
I/System.out: Adding request to queue: [ ] http://server/courses/267267267 0xebb503b0 NORMAL null
*onResponse never called*
The first time this request is made you can see that the onResponse() method is called and it returns the correct object. The signature of this 'correct' request is the exact same as the one above. The next time that exact request is made the onResponse is never called and I get no error.
I've looked at other posts on here but none of their solutions fixed the problem I am having and no error makes it hard to know what's going on.
Any help would be greatly appreciated.
Put:
System.out.println("JSON Success");
courseJSON = response;
into a separate method outside the callback and it works now. Not sure why...

How to disable returning volley network error?

Here is my code to ignore errors:
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError ignored) {
//nothing
}
});
But still it returns 403 error
E/Volley: [934] BasicNetwork.performRequest: Unexpected response code 403 for http://myawesome.site/login
E/Volley: [934] BasicNetwork.performRequest: Unexpected response code 403 for http://myawesome.site/login
Another problem is: above error shows twice in one call. It ignores DefaultRetryPolicy set to 0
Expecting your help.
To stop logging network activity, call the DevicePolicyManager method setNetworkLoggingEnabled() and pass false as the enabled argument.
Your DPC can call isNetworkLoggingEnabled() to check if network activity is currently logged.
reference link :https://developer.android.com/work/dpc/logging.html
check this section : Enable network logging.
I have solve problem by changing the method name. previously i am try to calling web service with POST method and I have changed to GET method then my problem solved. Try this solution by changing request method.
StringRequest stringRequest = new StringRequest(Request.Method.GET, "YOUR_WEBSERVICE_URL",
new Response.Listener<String>() {
#Override
public void onResponse(String response){}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {}
}) {
#Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<String, String>();
return params;
}
};
stringRequest.setRetryPolicy(new
DefaultRetryPolicy(60000,DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
requestQueue.add(stringRequest);

How to handle the response of Volley in Android

I use volley in the Android Activity, and make a request and got the response, but I want to handle the response maybe in an another method,but it won't work, what should i do ?
public class TestActivity extends Activity {
RequestQueue queue;
private String result;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String url = "www.google.com/something/I/need";
queue = Volley.newRequestQueue(this);
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// Do something with the response
Log.i("resp", response);
// I want to do sth with the response out of here
// maybe like this, let result = response
// and see the log at the end of the code
// but it failed, what should I do?
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// Handle error
Log.e("error", error.toString());
}
});
queue.add(stringRequest);
Log.e("result", result);
}
The Volley requests are asynchronous, so the program after sending the request, continues execution without waiting for the answer. So the code that processes the result is inserted into the OnResponse method. For more precise help explain why you would like to log out of the method OnResponse
Think about what you're doing: You're creating a StringRequest, then you add it to the request queue, but then you immediately try to check the result. Obviously, this won't work because the request hasn't been processed yet.
Your response will arrive in the onResponse method, and only then you'll be able to do something with it. You can set result = response here, but you'll only be able to see the value when the onResponse is called which could take some time.
Hope this clarifies things.

Unexpected response code 503 for Volley string request (using Amazon Web Service)

I'm making a string request with Volley. Here's the error:
basicNetwork.performRequest: Unexpected response code 503 for http://...
The problem is not the url. I've checked that already. The url is an address to some XML that looks like this for example:
<config>
<Request name="ValidateEmailRequest">
<requestqueue>emailrequest</requestqueue>
<responsequeue>emailresponse</responsequeue>
</Request>
<Request name="CleanEmail">
<requestqueue>Cleanrequest</requestqueue>
<responsequeue>Cleanresponse</responsequeue>
</Request>
</config>
Here is my request code:
StringRequest myReq = new StringRequest(
Request.Method.GET,
url,
new Response.Listener<String>()
{
/** On response **/
#Override
public void onResponse(String response) {
processData(response);
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
// handle error response
}
});
Is my request queue the problem? I'm making multiple request from different classes to the same static request queue, but that hasn't been a problem until now.
e.g.
MyOtherClass.getRequestQueue();
//Request code for this class...
MyOtherClass.RequestQueue.add(myRequest);
edit
My urls are working. They expire pretty fast because they are signed, but here is one anyways.
http://webservices.amazon.com/onca/xml?AWSAccessKeyId=AKIAJ6L6R4KOPIYIUXUA&Artist=Bill%20Evans%20Trio&AssociateTag=mytag-20&Operation=ItemSearch&SearchIndex=Music&Timestamp=2015-12-18T06%3A15%3A23Z&Title=Sunday%20At%20the%20Village%20Vanguard&Signature=QG97Kngo6khD7jAD0TUIXmy07SW0fmKTsrKnUsaBvYw%3D
HTTP Error 503 - Service unavailable
This means that networkResponse is null because in a TimeoutError no data is received from the server.
You can also check the error type from the following code.
Thanks to Submersed.
#Override
public void onErrorResponse(VolleyError error) {
if (error instanceof TimeoutError || error instanceof NoConnectionError) {
Toast.makeText(context,
context.getString(R.string.error_network_timeout),
Toast.LENGTH_LONG).show();
} else if (error instanceof AuthFailureError) {
//TODO
} else if (error instanceof ServerError) {
//TODO
} else if (error instanceof NetworkError) {
//TODO
} else if (error instanceof ParseError) {
//TODO
}
I think my problem was that I was making too many requests at the same time to the same product image on Amazon. As soon as I limited the number of request I made to the same product image, I stopped receiving the 503 error.

Categories

Resources