2323import org .json .JSONObject ;
2424import org .json .JSONTokener ;
2525
26+ import android .os .Message ;
27+
2628/**
2729 * Used to intercept and handle the responses from requests made using
2830 * {@link AsyncHttpClient}, with automatic parsing into a {@link JSONObject}
3638 * parent class.
3739 */
3840public class JsonHttpResponseHandler extends AsyncHttpResponseHandler {
41+ protected static final int SUCCESS_JSON_MESSAGE = 100 ;
42+
3943 //
4044 // Callbacks to be overridden, typically anonymously
4145 //
@@ -57,36 +61,54 @@ public void onSuccess(JSONObject response) {}
5761 */
5862 public void onSuccess (JSONArray response ) {}
5963
64+ public void onFailure (Throwable e , JSONObject errorResponse ) {}
65+ public void onFailure (Throwable e , JSONArray errorResponse ) {}
66+
6067
61- // Utility methods
62- @ Override
63- protected void handleSuccessMessage (String responseBody ) {
64- super .handleSuccessMessage (responseBody );
68+ //
69+ // Pre-processing of messages (executes in background threadpool thread)
70+ //
6571
72+ @ Override
73+ protected void sendSuccessMessage (String responseBody ) {
6674 try {
6775 Object jsonResponse = parseResponse (responseBody );
68- if (jsonResponse instanceof JSONObject ) {
69- onSuccess ((JSONObject )jsonResponse );
70- } else if (jsonResponse instanceof JSONArray ) {
71- onSuccess ((JSONArray )jsonResponse );
72- } else {
73- throw new JSONException ("Unexpected type " + jsonResponse .getClass ().getName ());
74- }
76+ sendMessage (obtainMessage (SUCCESS_JSON_MESSAGE , jsonResponse ));
7577 } catch (JSONException e ) {
76- onFailure (e , responseBody );
78+ sendFailureMessage (e , responseBody );
79+ }
80+ }
81+
82+
83+ //
84+ // Pre-processing of messages (in original calling thread, typically the UI thread)
85+ //
86+
87+ @ Override
88+ protected void handleMessage (Message msg ) {
89+ switch (msg .what ){
90+ case SUCCESS_JSON_MESSAGE :
91+ handleSuccessJsonMessage (msg .obj );
92+ break ;
93+ default :
94+ super .handleMessage (msg );
95+ }
96+ }
97+
98+ protected void handleSuccessJsonMessage (Object jsonResponse ) {
99+ if (jsonResponse instanceof JSONObject ) {
100+ onSuccess ((JSONObject )jsonResponse );
101+ } else if (jsonResponse instanceof JSONArray ) {
102+ onSuccess ((JSONArray )jsonResponse );
103+ } else {
104+ onFailure (new JSONException ("Unexpected type " + jsonResponse .getClass ().getName ()));
77105 }
78106 }
79107
80108 protected Object parseResponse (String responseBody ) throws JSONException {
81109 return new JSONTokener (responseBody ).nextValue ();
82110 }
83111
84- /**
85- * Handle cases where a failure is returned as JSON
86- */
87- public void onFailure (Throwable e , JSONObject errorResponse ) {}
88- public void onFailure (Throwable e , JSONArray errorResponse ) {}
89-
90112 @ Override
91113 protected void handleFailureMessage (Throwable e , String responseBody ) {
92114 if (responseBody != null ) try {
0 commit comments