-3

I'm using a library for android to do the HTTP communication between my app and my website. For the library, it allows you to create a static class which can then be called throughout the app.

What happens when you call the static class methods, basically you just pass your arguments to it and it does the rest (obviously). One of these arguments is AsyncHttpResponseHandler, which allows you to override methods and handle the different parts of the AsyncTask that its running.

Like so:

Static method inside class

public static void get(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
    client.get(getAbsoluteUrl(url, false), params, responseHandler);
}

And then when calling that method (as example):

TwitterRestClient.get("statuses/public_timeline.json", null, new JsonHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                // If the response is JSONObject instead of expected JSONArray
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONArray timeline) {
                // Pull out the first event on the public timeline
                JSONObject firstEvent = timeline.get(0);
                String tweetText = firstEvent.getString("text");

                // Do something with the response
                System.out.println(tweetText);
            }
        });

One of the methods that you can override is onFailure().

What i'm wondering is, is there a way that I can set a 'default' for the onFailure() override? I want to have it set the same for each time that I call the get(url, params, responseHandler) method without having to re-declare it each time, but i'm not aware of any way of setting it whilst still taking into account the passed AsyncHttpResponseHandler argument.

Matt Davis
  • 470
  • 5
  • 16

1 Answers1

1

You have to @Override onFailure() each time to tell each individual request if it must (or not) perform an onFailure success.

What you can do is create an utility method / class to handle all onFailure() requests.

EXAMPLE:

TwitterRestClient.get("statuses/public_timeline.json", null, new JsonHttpResponseHandler() {
    // other methods overrides

    @Override
    public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
        FailureClass.handlerMethod(statusCode, headers, responseBody, error);
    }
}

class FailureClass {
    public static handlerMethod(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
        // do the common stuff, redirect or what you want...
    }
}
Jordi Castilla
  • 26,609
  • 8
  • 70
  • 109
  • Thanks for this. Adds a bit more code than ideal but it works better than having to repeat the same handlerMethod code every single time! – Matt Davis Sep 15 '15 at 09:16