I'm working with an http-based API and want to know when I encounter any errors. I'm using Android-Query (stub):
AjaxCallback<JSONObject> cb = new AjaxCallback<JSONObject>() {
@Override
public void callback(String url, JSONObject json, AjaxStatus status) {
try {
if (json != null) {
if (json.getString("authenticated") != "true")
// An error, but status=200 and json!=null
} catch (JSONException e) { errors... } } };
And I'm using it like this:
final AQuery aq = new AQuery(this);
aq.ajax(url, JSONObject.class, cb);
cb.block();
My questions are:
cb.block()
is the only way to get the library to work synchronously, but I'm not sure it's the best way (it feels like it isn't).cb.getResult()
but it looks like calling this method causes the outside block to return (I can't explain it).Thanks.
So after I've spent some time with the library it looks like it supports synchronous HTTP requests. While I agree that this is not a best practice for most cases, saying that it's a bad idea altogether is ignoring some conditions that might require it. In my case I'm depended on other libraries which I cannot control, and this is off the UI thread, so it's ok.
AjaxCallback<JSONObject> cb = new AjaxCallback<JSONObject>();
final AQuery aq = new AQuery(this);
cb.url(url).type(JSONObject.class);
aq.sync(cb);
JSONObject json = cb.getResult();
AjaxStatus status = cb.getStatus();
if (json != null && statusValid(status)) {
// parse json object, throw if fails, etc.
}