How to read Volley Unexpected response code 500 - java

Hi guys I do not know how to read the actual detailed error message from the server, all I am getting is E/Volley: [73767] BasicNetwork.performRequest: Unexpected response code 500 for https://xxxx.com/xxxxx I saw people adding a onErrorResponse listener but mine isnt working so im clearly missing something, below is my code, any help is appreciated.
Request:
JSONObject jsonFavorites = new JSONObject();
String userId = Integer.toString(2);
String waypointID = Integer.toString(eventInfo.waypointId);
String waypointType = Integer.toString(eventInfo.stopType);
try {
jsonFavorites.put("action", favoriteAction);
jsonFavorites.put("uid", userId);
jsonFavorites.put("waypointid", waypointID);
jsonFavorites.put("waypoint_type", waypointType);
//fetchData(bounds);
} catch (Exception e) {
}
try{
GetUserFavoritesRequest favoritesRequest = new GetUserFavoritesRequest(jsonFavorites, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//Parse the response that was received from the server.
Log.d("Maps:", " Parsing Response");
try {
Log.i("tagconvertstr", "[" + response + "]");
//List<String> allFavorites = new ArrayList<String>();
JSONArray cast = new JSONArray(response);
if(userFavoritewaypointId.contains(eventInfo.waypointId)){
favoriteAction = "remove";
infoFavoriteButton.setImageResource(R.drawable.favorites_disabled);
}else{
favoriteAction = "add";
infoFavoriteButton.setImageResource(R.drawable.favorites);
}
finished = true;
} catch (JSONException e) {
//adding or removing favorites was unsuccessful.
Log.d("Maps:", " Failed getting a response from server for adding or removing favorites");
e.printStackTrace();
//Set the finished flag to true to let everyone know that we
//finished receiving a response from the server.
finished = true;
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//Parse the response that was received from the server.
NetworkResponse networkResponse = error.networkResponse;
if (networkResponse != null) {
Log.e("Volley", "Error. HTTP Status Code:"+networkResponse.statusCode);
}
if (error instanceof TimeoutError) {
Log.e("Volley", "TimeoutError");
}else if(error instanceof NoConnectionError){
Log.e("Volley", "NoConnectionError");
} else if (error instanceof AuthFailureError) {
Log.e("Volley", "AuthFailureError");
} else if (error instanceof ServerError) {
Log.e("Volley", "ServerError");
} else if (error instanceof NetworkError) {
Log.e("Volley", "NetworkError");
} else if (error instanceof ParseError) {
Log.e("Volley", "ParseError");
}
Log.d("Maps:", " Error: " + error.getMessage());
finished = true;
}
});
RequestQueue queue = Volley.newRequestQueue(getActivity());
queue.add(favoritesRequest);
} catch (Exception e) {
//We failed to start a login request.
Log.d("Maps:", " Failed to start response for adding or removing favorites");
//Set the finished flag to true to let everyone know that we
//finished receiving a response from the server.
finished = true;
}
GetUserFavoritesRequest.java
public class GetUserFavoritesRequest extends StringRequest {
private static final String LOGIN_REQUEST_URL = "https://xxxx.com/xxxxx";
private Map<String, String> params;
public GetUserFavoritesRequest(JSONObject getFavorites, Response.Listener<String> listener, Response.ErrorListener errorListener){
super(Request.Method.POST, LOGIN_REQUEST_URL, listener, null);
params = new HashMap<>();
try {
if(getFavorites.get("action").toString().equals("get")){
Log.d("Maps: ", "Looks like we are retrieving a list of favorite waypoints");
params.put("action", getFavorites.get("action").toString());
params.put("uid", getFavorites.get("uid").toString());
}else if(getFavorites.get("action").toString().equals("add")){
Log.d("Maps: ", "Looks like we are adding a favorite waypoint" + getFavorites);
params.put("action", getFavorites.get("action").toString());
params.put("uid", getFavorites.get("uid").toString());
params.put("waypointid", getFavorites.get("waypointid").toString());
params.put("waypoint_type", getFavorites.get("waypoint_type").toString());
}else if(getFavorites.get("action").toString().equals("remove")) {
Log.d("Maps: ", "Looks like we are removing a favorite waypoint" + getFavorites);
params.put("action", getFavorites.get("action").toString());
params.put("uid", getFavorites.get("uid").toString());
params.put("waypointid", getFavorites.get("waypointid").toString());
params.put("waypoint_type", getFavorites.get("waypoint_type").toString());
}
}catch (Exception e){
}
}
#Override
public Map<String, String> getParams() {
return params;
}
}

I think there might be a mistake in GetUserFavoritesRequest's constructor
super(Request.Method.POST, LOGIN_REQUEST_URL, listener, null);
change null to errorListener.

Related

Volley multiple requests to server in Android studio

I'm using volley for my post requests and the issue is when I send 362 requests on queue to the server the data will save even though there's an error response as I assumed, or there are repeating data stored in the database.Sometimes my network connectivity is slow. Let's say I send 362 data to my server and I have 3 error response, when the sync was done the overall total of the saved data is still 362 and it should 359 since I have 3 error response, currently I have condition when the error response received the data should not save to the server.
This is what I've tried
StringRequest request = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject data = new JSONObject(response);
String status = data.getString("status");
String description = data.getString("description");
JSONObject dataObject = data.getJSONObject("data");
String household = dataObject.getString("hh_id");
if (status.matches("success")){
progressCC[0]++;
progressPercent = findViewById(R.id.progressCount);
progressBar = findViewById(R.id.progressBar);
progressCount = findViewById(R.id.progressFigure);
Double progressCalc = progressCC[0] / countEmvDetails * 100;
progressCount.setText(String.valueOf(progressCC[0].intValue()));
progressPercent.setText(String.valueOf(progressCalc.intValue()));
progressBar.setProgress(progressCalc.intValue());
lst.add(description + "household id: " + household);
gvMain.setAdapter(adapter);
if (progressPercent.getText().toString().matches("100")) {
Toasty.success(SyncData.this, "Completed", Toast.LENGTH_SHORT, true).show();
Toasty.success(SyncData.this, "Updating local data please wait!", Toast.LENGTH_SHORT, true).show();
updaterEmvMonitoring();
}
sqLiteHelper.storeLogs("sync", hh_id);
sqLiteHelper.deleteEmvMonitoringDetails(id);
}
else{
btnSync.setEnabled(true);
lst2.add("Error on syncing the data!");
gvMain2.setAdapter(adapter2);
Toasty.error(getApplicationContext(), "Error on pulling data.", Toast.LENGTH_SHORT, true).show();
}
} catch (JSONException e) {
btnSync.setEnabled(true);
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// method to handle errors.
btnSync.setEnabled(true);
sqLiteHelper.storeLogs("error", hh_id);
try {
String responseBody = new String(error.networkResponse.data, "utf-8");
Integer responseCode = error.networkResponse.statusCode;
if (responseCode == 401) {
JSONObject data = new JSONObject(responseBody);
JSONArray errors = data.getJSONArray("errors");
JSONObject jsonMessage = errors.getJSONObject(0);
String message = jsonMessage.getString("message");
Toasty.warning(SyncData.this, message, Toast.LENGTH_SHORT, true).show();
lst2.add(message);
gvMain2.setAdapter(adapter2);
} else if (responseCode == 404) {
JSONObject data = new JSONObject(responseBody);
String desc = data.getString("description");
Toasty.error(SyncData.this, "Error 404:" + desc, Toast.LENGTH_SHORT, true).show();
lst2.add(desc);
gvMain2.setAdapter(adapter2);
}
} catch (Exception e) {
Log.d("Error co", String.valueOf(e));
lst2.add(String.valueOf(e));
gvMain2.setAdapter(adapter2);
Toasty.error(SyncData.this, "Network not found.", Toast.LENGTH_SHORT, true).show();
}
}
}) {
#Override
public Map<String, String> getHeaders() {
Map<String, String> headers = new HashMap<>();
headers.put("Authorization", "Bearer " + token);
return headers;
}
protected Map<String,String> getParams(){
Map<String, String> params = new HashMap<>();
params.put("full_name", full_name);
return params;
}
};
request.setRetryPolicy(new DefaultRetryPolicy(
DefaultRetryPolicy.DEFAULT_TIMEOUT_MS * 5,
0,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
queue.add(request);

Volley not recieving http response but postman is

I send the /getsms GET request to an API and I get the expected results on postman. However, when I try to make the same request through volley in java on android studio, it just doesn't get a response, I keep waiting and nothing happens.
I'm sure the API does get the request since the expected changes occur when I send the data associated with the get request.
So I'm at a loss as to why exactly it doesn't get a response.
Java code:
final String url = "http://10.0.2.2:3000/myroute/getsms/"+frm;
JsonObjectRequest getRequest = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>()
{
#Override
public void onResponse(JSONObject response) {
try {
String frm = response.getString("src_num");
String msg = response.getString("msg");
int id = response.getInt("id");
itemsAdapter.add(frm + ": " + msg);
Log.d("Response", response.toString());
}
catch (Exception err) {
Log.d("excpetion", err.toString());
}
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
Log.d("Error.Response", error.toString());
}
}
);
API code:
router.get('/getsms/:dest_num', function (req, res) {
console.log("get oldest unsent sms from db");
let sql = "SELECT * FROM " + table + " WHERE " + "dest_num=" + req.params.dest_num + " AND sent=FALSE " + "ORDER BY id " + "LIMIT 1;";
console.log(sql);
db.mycon.query(sql, function (err, result) {
console.log("Result: " + JSON.stringify(result));
if(err){
res.send(err);
} else {
console.log("SENT!")
res.json(result);
}
});
});
Any help is appreciated.
UPDATE: So upon sifting through the logs I found this:
2020-01-15 22:07:23.481 11880-11880/com.example.sms D/Error.Response: com.android.volley.ParseError: org.json.JSONException: Value [{"id":4,"src_num":"321","dest_num":"1003435365","msg":"first message from server","time":100,"sent":0}] of type org.json.JSONArray cannot be converted to JSONObject
Apparently the response is received but Volley kicks when parsing. I cant see why this is happening. I don't see anything wrong with the JSON string. And is this really enough for it to not go into the onResponse function?
UPDATE2: So apparently that was indeed the problem and what was sent wasn't a JSONObject but a JSONArray. and just needed to change the datatypes accordingly.
So the code ended working with:
String url = "http://10.0.2.2:3000/myroute/getsms/" + frm;
JsonArrayRequest jsonObjectRequest = new JsonArrayRequest(Request.Method.GET, url, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response_arr) {
try {
JSONObject response = response_arr.getJSONObject(0);
String frm = response.getString("src_num");
String msg = response.getString("msg");
int id = response.getInt("id");
itemsAdapter.add(frm + ": " + msg);
} catch (Exception err) {
System.out.println(err.toString());
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("Error.Response", error.toString());
}
});
requestQueue.add(jsonObjectRequest);
Thanks to the comments for helping :)
You can try for The code given below and also add the request to the requestqueue of the new instance of RequestHandler.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray array = new JSONArray(response); //here is the mistake of parsing which will be removed after it is converted to the json object
JSONObject object = array.getJSONObject(0); //-----mistake
String frm = object.getString("src_num");
String msg = object.getString("msg");
int id = object.getInt("id");
itemsAdapter.add(frm + ": " + msg);
Log.d("Response", response.toString());
} catch (JSONException e) {
Log.d("excpetion", err.toString());
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("Error.response", err.toString());
}
});
new RequestHandler().addToRequestQueue(stringRequest);
Hope it helps !!

android volley: global variables does not change depending on the response on first time execution of method.

I have method in which i am making a volley request and depending on the response I need to change a global boolean variable but for some reason the variable only gets changed after the method is executed completely giving me wrong data for the variable. I need to somehow changed the variable only after the response is recieved.. please help me with it
I need to change the value of variable 'chk' on response but it does not change.
public boolean checkSourceCode() {
pDialog.setMessage("Please Wait ...");
pDialog.show();
final String entered_source_code = source_code.getText().toString();
if(entered_source_code!=null || !entered_source_code.isEmpty()) {
testString = entered_source_code;
final StringRequest sr = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String web_response) {
try {
response = new JSONObject(web_response);
Log.e("Resp SUCCESS", "" + response);
} catch (JSONException e) {
e.printStackTrace();
}
try {
hasBeenValidated = true;
if (response.getBoolean("success")) {
Log.e("Resp SUCCESS", "" + response);
validateCode = true;
chk=true; // THIS VALUE DOES NOT CHANGE ON FIRST CALL OF THE METHOD HOWEVER ON SECOND TIME CALLING THE METHOD IT CHANGED
// Utils.reference_id = source_code.getText().toString().trim();
pDialog.hide();
input_layout_source_code.setError(null);
input_layout_source_code.setErrorEnabled(false);
Utils.reference_id = source_code.getText().toString().trim();
source_code.setBackground(source_code.getBackground().getConstantState().newDrawable());
} else {
validateCode = false;
chk=false;// THIS VALUE DOES NOT CHANGE ON FIRST CALL OF THE METHOD HOWEVER ON SECOND TIME CALLING THE METHOD IT CHANGED
pDialog.hide();
input_layout_source_code.setErrorEnabled(true);
input_layout_source_code.setError("Invalid reference Id.");
Utils.reference_id = null;
Toast.makeText(getContext(), "Invalid reference Id", Toast.LENGTH_SHORT).show();
}
// chk = validateSourceCode();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
String json = null;
if (error instanceof NoConnectionError) {
String strerror = "No internet Access, Check your internet connection.";
displayMessage(strerror);
}
NetworkResponse response = error.networkResponse;
if (null != response && response.statusCode != 200) {
Log.e("Resp code", "" + response.statusCode);
displayMessage("Please contact administrator for error code " + response.statusCode);
}
if (response != null && response.data != null) {
switch (response.statusCode) {
case 400:
json = new String(response.data);
json = trimMessage(json, "message");
if (json != null) displayMessage(json);
break;
default:
json = new String(response.data);
json = trimMessage(json, "message");
if (json != null) displayMessage(json);
}
}
}
}
) {
#Override
public Request.Priority getPriority() {
return Priority.IMMEDIATE;
}
#Override
protected Map<String, String> getParams() {
Map<String, String> requestParams = new HashMap<String, String>();
requestParams.put("referral_code", entered_source_code);
// params.put("email", "abc#androidhive.info");
// params.put("password", "password123");
return requestParams;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("Auth-Token", auth_token);
return params;
}
};
sr.setRetryPolicy(new DefaultRetryPolicy(
60000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
// Adding request to request queue
MaintainRequestQueue.getInstance(mContext).addToRequestQueue(sr, "tag");
}
else{
pDialog.hide();
chk=true;// THIS VALUE DOES NOT CHANGE ON FIRST CALL OF THE METHOD HOWEVER ON SECOND TIME CALLING THE METHOD IT CHANGED
}
Toast.makeText(mContext, String.valueOf(chk), Toast.LENGTH_LONG).show();
return chk;
}
chk variable can not reinitialize again inside a thread
try this
setchk(boolean chk)
{
this.chk=chk;
}
and call it from request method;
Your variable inside the volley request is not initialized by the time you reach: Toast.makeText(mContext, String.valueOf(chk), Toast.LENGTH_LONG).show(); Use a get method to obtain the chk value within volley and call that getter where you need it.

Facebook SDK email and gender is given Null in android

Dear developers I'm try to save data from Facebook I'm getting other all data but can't get the email and gender.
This is my code
loginButton.setReadPermissions("public_profile");
loginButton.setReadPermissions("email");
loginButton.setReadPermissions("user_friends");
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
AccessToken accessToken = loginResult.getAccessToken();
GraphRequest request = GraphRequest.newMeRequest( loginResult.getAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object,GraphResponse response) {
if (response != null) {
try {
email = object.getString("email");
} catch (JSONException e) {
e.printStackTrace();
}
try {
gender = object.getString("gender");
} catch (JSONException e) {
e.printStackTrace();
}
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "email,gender");
request.setParameters(parameters);
request.executeAsync();
Profile profile = Profile.getCurrentProfile();
userid = profile.getId();
userfirstname = profile.getFirstName();
middlename = profile.getMiddleName();
userlastname = profile.getLastName();
userimage = profile.getProfilePictureUri(30, 40);
linkuri = profile.getLinkUri();
name = profile.getName();
new AsyncTask<String, String, String>() {
#Override
protected String doInBackground(String... params) {
WebService ws = new WebService(URL);
Map<String, String> data = new HashMap<String, String>();
data.put("user_fb_id", userid);
data.put("first_name", userfirstname);
data.put("middle_name", userfirstname);
data.put("gender", gender);
data.put("email", email);
data.put("last_name", userfirstname);
data.put("user_fb_profile_name", name);
data.put("fb_profile_pic", userimage.toString());
try {
String response = ws.makeHTTPRequest(data, "POST");
JSONObject jsonObject = new JSONObject(response);
Log.e("Response", jsonObject.toString());
} catch (Exception e) {
Log.d("", "Exception : " + e.getMessage());
}
return null;
}
}.execute();
}
#Override
public void onCancel() {
//info = ("Login attempt canceled.");
}
#Override
public void onError(FacebookException e) {
// info = ("Login attempt failed.");
}
});
now I will let you know what is the error in my above code.
when i run the GraphRequest it will execute successfully but didn't get the email and gender. The email and gender is equal to null After the GrapRequest method i am running AsyncTask and send that data in my web services post class my class give me error of null email and gender but when i hover the email and gender after execution of AsyncTask they have that data please help me how to solve that issue.
what i want i want to store the user basic data if there is another way also let me know that i will try.
The problem occurs because In your code two Asynctask runs simultaneously.
Means that the GraphRequest class also runs an asynctask to get user data and you are also running a async to send the user data to server.
Async tasks always runs on separate thread(not on Main thread) and they don't wait for completion of other task.
So the solution is call your Async task in onCompleted() method. LIKE..
Write this async class for upload data to server outside of registerCallback.
private class Upload_Data extends AsyncTask<String, String, String>() {
#Override
protected String doInBackground(String... params) {
WebService ws = new WebService(URL);
Map<String, String> data = new HashMap<String, String>();
data.put("user_fb_id", userid);
data.put("first_name", userfirstname);
data.put("middle_name", userfirstname);
data.put("gender", gender);
data.put("email", email);
data.put("last_name", userfirstname);
data.put("user_fb_profile_name", name);
data.put("fb_profile_pic", userimage.toString());
try {
String response = ws.makeHTTPRequest(data, "POST");
JSONObject jsonObject = new JSONObject(response);
Log.e("Response", jsonObject.toString());
} catch (Exception e) {
Log.d("", "Exception : " + e.getMessage());
}
return null;
}
}
then call this async class in onCompleted method after getting the email and gender value and also check that email and gender is not null before calling Asynctask class.
#Override
public void onCompleted(JSONObject object,GraphResponse response) {
if (response != null) {
try {
email = object.getString("email");
} catch (JSONException e) {
e.printStackTrace();
}
try {
gender = object.getString("gender");
} catch (JSONException e) {
e.printStackTrace();
}
}
if(email!=null && gender!=null){
new Upload_Data().execute();
}
}
});
Hope this will helpful.

Volley JSONException: End of input at character 0 of

I've seen others come across this problem, but none of the posts have been able to assist me. I'm attempting to use Volley for my REST call library, and when I'm attempting to use a Put call with a JSON Object as a parameter, I'm getting error with: org.json.JSONException: End of input at character 0 of.
Here is the code:
protected void updateClientDeviceStatus(Activity activity, final int status) {
JSONObject jsonParams = new JSONObject();
try {
jsonParams.put("statusId", String.valueOf(status));
} catch (JSONException e1) {
e1.printStackTrace();
}
Log.i(LOG_TAG, "json: " + jsonParams.toString());
String url = Constants.API_URL + "client/device/" + getDeviceId();
// Request a response from the provided URL.
JsonObjectRequest request = new JsonObjectRequest
(Request.Method.PUT, url, jsonParams, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.i(LOG_TAG, "updated client status");
Log.i(LOG_TAG, "response: " + response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.i(LOG_TAG, "error with: " + error.getMessage());
if (error.networkResponse != null)
Log.i(LOG_TAG, "status code: " + error.networkResponse.statusCode);
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("User-Agent", getUserAgent());
params.put("X-BC-API", getKey());
return params;
}
#Override
public String getBodyContentType() {
return "application/json";
}
};
request.setRetryPolicy(new DefaultRetryPolicy(20000, 3, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
MySingleton.getInstance(activity).addToRequestQueue(request);
}
}
The jsonParams log displays:
json: {"statusId":"1"}
Is there another setting that I'm missing? It appears that the request can't parse the JSON Object. I even tried creating a HashMap and then using that to create a JSON Object, but I still get the same result.
I also have encountered this issue.
It's not necessarily true that this is because a problem on your server side - it simply means that the response of the JsonObjectRequest is empty.
It could very well be that the server should be sending you content, and the fact that its response is empty is a bug. If, however, this is how the server is supposed to behave, then to solve this issue, you will need to change how JsonObjectRequest parses its response, meaning creating a subclass of JsonObjectRequest, and overriding the parseNetworkResponse to the example below.
#Override
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
try {
String jsonString = new String(response.data,
HttpHeaderParser.parseCharset(response.headers, PROTOCOL_CHARSET));
JSONObject result = null;
if (jsonString != null && jsonString.length() > 0)
result = new JSONObject(jsonString);
return Response.success(result,
HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JSONException je) {
return Response.error(new ParseError(je));
}
}
Keep in mind that with this fix, and in the event of an empty response from the server, the request callback will return a null reference in place of the JSONObject.
Might not make sense but nothing else worked for me but adding a content-type header
mHeaders.put("Content-Type", "application/json");
In my case it was simply the request I was sending(POST) was not correct. I cross-checked my fields and noted that there was a mismatch, which the server was expecting to get thus the error->end of input at character 0 of...
I had the same problem, I fixed it by creating a custom JsonObjectRequest that can catch a null or empty response :
public class CustomJsonObjectRequest extends JsonObjectRequest {
public CustomJsonObjectRequest(int method, String url, JSONObject jsonRequest, Response.Listener<JSONObject> listener, Response.ErrorListener errorListener) {
super(method, url, jsonRequest, listener, errorListener);
}
public CustomJsonObjectRequest(String url, JSONObject jsonRequest, Response.Listener<JSONObject> listener, Response.ErrorListener errorListener) {
super(url, jsonRequest, listener, errorListener);
}
#Override
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
try {
String jsonString = new String(response.data,
HttpHeaderParser.parseCharset(response.headers));
JSONObject result = null;
if (jsonString != null && jsonString.length() > 0)
result = new JSONObject(jsonString);
return Response.success(result,
HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JSONException je) {
return Response.error(new ParseError(je));
}
}
Then just replace the default JsonObjectRequest by this one !
You need to check if the server response is not empty. Maybe it could be a emtply String "".
if (response.success()) {
if (response.getData() == null) {
return null;
} else if (response.getData().length() <= 0){
return null;
}
// Do Processing
try {
I have faced the same problem, there was just a small silly mistake that happened.
instead of
val jsonObject = JSONObject(response.body()?.string())
should be
val jsonObject = JSONObject(response.body()!!.string())

Categories