1

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:

  • I've found that using 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).
  • The callback method can't throw exceptions, can't return anything (void) etc, so what is the best way to handle errors? I noticed it supports cb.getResult() but it looks like calling this method causes the outside block to return (I can't explain it).

Thanks.

Bishan
  • 15,211
  • 52
  • 164
  • 258
asafge
  • 1,139
  • 1
  • 14
  • 21
  • `block()` is a bad way, m'kay ... [callback fail when `json` is null](https://code.google.com/p/android-query/#JSON_Example) ... i'm not sure but you can also check `status` – Selvin Jul 05 '13 at 14:00
  • @Selvin Any suggestion instead of block()? I want to wait for the transaction to end and let the UI know it has objects to display. – asafge Jul 05 '13 at 14:04
  • put your code to `AjaxCallback>.callback(...)` – Selvin Jul 05 '13 at 14:05
  • I hope this makes the question clearer – asafge Jul 05 '13 at 14:13

1 Answers1

3

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.
}
asafge
  • 1,139
  • 1
  • 14
  • 21