I have implemented a custom request using volley in order to login to a webserver.
This is the function im using:
private void volleyTest2(String username, String password, String deviceid) {
Map<String, String> params;
params = new HashMap<>();
params.put("username", username);
params.put("password", password);
//params.put("device_id", deviceid);
params.put("device_id", "H767A76S7D6D");
Volley.newRequestQueue(MainActivity.this).add(
new CustomJsonRequest(Request.Method.POST, URL, params,
new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
String output="";
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
output+=obj.getString("name") + " "+ obj.getString("surname");
} catch (JSONException e) {
e.printStackTrace();
}
}
Toast.makeText(getApplicationContext(), "Benvenuto, " + output, Toast.LENGTH_LONG).show();
showProgress(false);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("Error: " + error.getMessage());
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
showProgress(false);
}
}
)
{
@Override
protected Response parseNetworkResponse(NetworkResponse response) {
try {
String jsonString = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
return Response.success(new JSONArray(jsonString), HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JSONException je) {
return Response.error(new ParseError(je));
}
}
}
);
}
And this is my CustomJsonRequest:
public class CustomJsonRequest extends Request {
Map<String, String> params;
private Response.Listener listener;
public CustomJsonRequest(int requestMethod, String url, Map<String, String> params, Response.Listener responseListener, Response.ErrorListener errorListener) {
super(requestMethod, url, errorListener);
this.params = params;
this.listener = responseListener;
}
@Override
protected void deliverResponse(Object response) {
listener.onResponse(response);
}
@Override
public Map<String, String> getParams() throws AuthFailureError {
return params;
}
@Override
protected Response parseNetworkResponse(NetworkResponse response) {
try {
String jsonString = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
return Response.success(new JSONObject(jsonString), HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JSONException je) {
return Response.error(new ParseError(je));
}
}
}
Since i can not edit the php side this is the scenario:
- if the login is correct i receive a JSONArray
- if the login ain't correct i receive a JSONObject like this:
My only issue is that if the login is incorrect i receive this error:
Error: org.json.JSONException: Value {"error":"Username\/password non trovati"} of type org.json.JSONObject cannot be converted to JSONArray
So how can I handle the incorrect login if I get a JSONObject instead of a JSONArray ?
I'd like to show only the content inside the Object, so: "Username\/password non trovati"
UPDATE1:
private void volleyTest2(String username, String password, String deviceid) {
Map<String, String> params;
params = new HashMap<>();
params.put("username", username);
params.put("password", password);
//params.put("device_id", deviceid);
params.put("device_id", "H767A76S7D6D");
Volley.newRequestQueue(MainActivity.this).add(
new CustomJsonRequest(Request.Method.POST, URL, params,
new Response.Listener<JsonElement>() {
@Override
public void onResponse(JsonElement element) {
String output="";
// Parsing json
if(element.isJsonArray()){
JsonArray array=element.getAsJsonArray();
//read response here
Log.d(TAG,"array.toString(): " + array.toString());
}else if(element.isJsonObject()){
JsonObject object=element.getAsJsonObject();
//read response here
Log.d(TAG,"object.toString(): " + object.toString());
}
Toast.makeText(getApplicationContext(), "Benvenuto, " + output, Toast.LENGTH_LONG).show();
showProgress(false);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("Error: " + error.getMessage());
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
showProgress(false);
}
}
)
{
@Override
protected Response parseNetworkResponse(NetworkResponse response) {
try {
String jsonString = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
return Response.success(new JSONArray(jsonString), HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JSONException je) {
return Response.error(new ParseError(je));
}
}
}
);
}
Possiblities
1. Make request return type as com.google.gson.JsonElement.class and check like this
@Override
public void onResponse(JsonElement element) {
if(element.isJsonArray()){
JsonArray array=element.getAsJsonArray();
//read response here
}else if(element.isJsonObject()){
JsonObject object=element.getAsJsonObject();
//read response here
}
}
2. Make String request try to convert it JSONArray or JSONObject. while converting catch those exceptions if occurred ( JSONException : JSONObject cannot be converted to JSONArray) .
3. Make StringRequest and parse response to JsonElement and check whether its JsonObject or JsonArray
@Override
public void onResponse(String s) {
JsonParser parser = new JsonParser();
JsonElement element = parser.parse(s);
if (element.isJsonArray()) {
JsonArray array = element.getAsJsonArray();
//read response here
} else if (element.isJsonObject()) {
JsonObject object = element.getAsJsonObject();
//read response here
}
}
4. Best way : Change server code :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With