I have integrated android volley lib for node js rest service calls. If I get response success it returns status code 200 and response JSON object which is working.
But if I get any 400(401,409, etc) and 500(500,504, etc) related error it is not showing error response coming from service instead it showing
Volley.error(service sending {status:false,message:"enter password"}
this error object but I am unable to read this message).
How to read error response coming from node js service using volley lib.
In onErrorResponse() method write the below code:
NetworkResponse networkResponse = error.networkResponse;
if (networkResponse != null && networkResponse.data != null) {
try {
String jsonError = new String(networkResponse.data);
Log.d(TAG, "jsonError: " + jsonError);
JSONObject errorObject = new JSONObject(jsonError);
// Here you can do whatever you want with JSONError.
Snackbar snackbar = Snackbar.make(mActivitySingleSellerBinding.relativeLayoutRoot, errorObject.getString("message"), Snackbar.LENGTH_LONG);
snackbar.show();
} catch (JSONException e) {
e.printStackTrace();
}
}
This errorObject.getString("message"); will give you the error string.
Related
I'm using RazorPay sdk 1.6.18 in android mobile app
#Override
public void onPaymentError(int code, String response, PaymentData data) {
try {
System.out.println("Payment Error");
String errorMsg = null;
JSONObject jsonObject = new JSONObject(response);
if(jsonObject.has("error")) {
JSONObject errorJson = jsonObject.getJSONObject("error");
if(errorJson.has("description"))
errorMsg = errorJson.getString("description");
}
Toast.makeText(this, errorMsg, Toast.LENGTH_LONG).show();
} catch(Exception e) {
FirebaseCrashlytics.getInstance().recordException(e);
}
}
in onPaymentError() String response is getting empty & it's throwing exception
org.json.JSONException
End of input at character 0 of
We got this issue from crashlytics & it's affecting few users in production.
Does anybody have any clue in which case response will be empty & what's a better way to handle this?
Just Try,
Response strings must be checked for empty, null, or "null" status before being assigned a JSON object. then turn the response string into a JSON object. able to prevent crashes
Looked around but couldn't find solution to this.
Checking status code via following code:
JsonObjectRequest req = new JsonObjectRequest(URL, null,
response -> {
Log.d("Response", response.toString(4));
},error -> {
NetworkResponse networkResponse = error.networkResponse;
if (networkResponse != null) {
if (error.networkResponse.statusCode == 204) {
Toast.makeText(Customers.this, "No Content!",Toast.LENGTH_LONG).show();
//This is where I want request to return when no content.
}
}else{
//Null Network Response, request returns in this section
}
}
When I send 204 Status code from server, which is for NO_CONTENT, request returns in error section and with network response NULL so I can't check if it was NO_CONTENT error or internet issue or some other.
Let me know if anyone can help.
Thanks
There was issue with server side logic. It worked after fixing that. Thanks everyone.
I have created an Android Application and trying to update profile with data base.
if (response.isSuccessful()) {
Log.d("TAG", "response: "+response.body().string());
String result = response.body().string();
JSONObject jsonObj = new JSONObject(result);
if(jsonObj.has("status")){
if(jsonObj.get("status").equals("success")){
Snackbar snackbar = Snackbar
.make(layout, "User details successfully updated",
Snackbar.LENGTH_LONG);
snackbar.show();
} else {
Log.d("TAG","CLICK Failed");
buttonVisible();
}
When i tried to Log the response, I am getting TAG: response: {"status":"success","message":"User details successfully updated."}
but when i tried to convert response.body().string(); to string I am getting this error**org.json.JSONException: End of input at character 0 of** . can you please tell me how I can solve this problem?
Try to put
String result = response.body().string();
before
Log.d("TAG", "response: "+response.body().string());
Such that it looks like
String result = response.body().string();
Log.d("TAG", "response: "+result);
Just in case someone bumps into the same weird thing as I have. I run my code during development in Debug Mode and apparently since OKHttp 2.4
..the response body is a one-shot value that may be consumed only once
So when in debug there is a call "behind the scene" from the inspector and the body is always empty. See: http://square.github.io/okhttp/2.x/okhttp/com/squareup/okhttp/Response.html
In Log print your string object like :
String result = response.body().string();
Log.d("TAG", "response: "+result);
I am using retrofit lib because it's giving fast response.
But why need always one model class corresponding one ws response of parsing/calling web service using retrofit. Is it possible to get json response directly in my program?
You can wrap your response inside Response and then access the JSON data using the following:
call.enqueue(new Callback<ResponseBody>() {
#Override
onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
if (response.isSuccessful()) {
// Do your success stuff...
} else {
try {
JSONObject jObjError = new JSONObject(response.errorBody().string());
Toast.makeText(getContext(), jObjError.getString("message"), Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(getContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}
}
Yes, you can. Use this as your api call:
Call<ResponseBody> yourMethod(). Then in your onResponse callback you can get json response via response.body().string(). See javadoc.
When I use OkHttp to post I get a response like this (Instagram api)
{"access_token":"2222222.22222.2222222","user":{"username":"xxx","bio":"","website":"","profile_picture":"https:\/\/instagramimages-a.akamaihd.net\/profiles\/anonymousUser.jpg","full_name":"Test","id":"222222"}}
which I am unable to cast to a JsonObject (I think it is because of the weird way the urls are formatted).
But when I use HttpsUrlConnection everything works fine.
OkHTTP
private final OkHttpClient client = new OkHttpClient();
public static final MediaType MEDIA_TYPE_MARKDOWN
= MediaType.parse("text/plain");
//then in a function
String postBody="client_id="+Application.INSTAGRAM_CLIENT_ID
+"&client_secret="+Application.INSTAGRAM_SECRET_KEY
+"&grant_type=authorization_code"
+"&redirect_uri=" +Application.CALLBACKURL
+"&code=" + SharedPrefHelper.getSharedPerferenceData(context, SharedPrefHelper.SHARED_PREFERENCE_KEY_INSTAGRAM_CODE, "");
Request request = new Request.Builder()
.url(Application.TOKENURL)
.post(RequestBody.create(MEDIA_TYPE_MARKDOWN,postBody))
.build();
I use response.body.string() in the callback method to get the string and cast it to JsonObject.
if (response.code() == 200) {
try {
JSONObject jsonObject = new JSONObject(response.body().string());
} catch (JSONException e) {
}
}
How to fix this ?
ERROR :
org.json.JSONException: End of input at character 0 of
You can only use response.body().string() only once. I was calling it twice. First for logging the response and then again for json casting.
First thing:
You are probably getting a blank response. Its not null but the response is empty. So you are getting this error and not a NullPointerException
Have you logged it before converting in JSON? Checked it.
Second Thing:
You may have to try with GET if you are used POST currently or Vice Versa.