I have the following lines:
Consumer<JSONObject> OnSuccess; // Defined somewhere else...
JsonParameters = jsonParameters; // Defined somewhere else...
String targetUrl = BaseService.BuildUrl(BASE_TARGET_URL, TargetMethod);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest
(
Request.Method.POST,
targetUrl,
JsonParameters,
response -> {
OnSuccess.accept(response);
},
error -> {
Toast.makeText(BaseService.BaseContext,
"ERROR: COMS NOT WORKING", Toast.LENGTH_LONG).show();
}
)
};
In this specific case, I am reaching the server to obtain an object from the DB. When the object on the server side exists, the code on java hits the method OnSuccess
, however, when the server, simply returns a null
object (there are no errors on the server, It is simply returning a null
object, if this is the case) then my java code is hitting the "onError
"....
But for me this is plain wrong, because I want the onError to just happen when there is really an error (or because the server is down, or the DB is down, or some exception along the way happens), NOT when the server returns a simply null
object.
What is the easiest way to solve this problem in java ? I do not want to change the server to return me an empty object (not null
)....
Thanks
I think Volley's JsonObjectRequest
is specifically designed to handle JSON objects. In case the server returns null
value then it is normal that the onError
callback is invoked because, as you said in the comment, null
cannot be converted to JSONObject
.
My suggestion is to use a less strict Volley object request, like for instance StringRequest
. When the onSuccess
is hit and when the result is not null
convert the resulting code into a JSONObject
:
JSONObject jsonResp = new JSONObject(response);
OnSuccess.accept(jsonResp);
Conversely, when the response is null
, then you can treat it as your needs (and of course avoid to create JSONObject as above)