23
23
import org .json .JSONObject ;
24
24
import org .json .JSONTokener ;
25
25
26
+ import android .os .Message ;
27
+
26
28
/**
27
29
* Used to intercept and handle the responses from requests made using
28
30
* {@link AsyncHttpClient}, with automatic parsing into a {@link JSONObject}
36
38
* parent class.
37
39
*/
38
40
public class JsonHttpResponseHandler extends AsyncHttpResponseHandler {
41
+ protected static final int SUCCESS_JSON_MESSAGE = 100 ;
42
+
39
43
//
40
44
// Callbacks to be overridden, typically anonymously
41
45
//
@@ -60,20 +64,33 @@ public void onSuccess(JSONArray response) {}
60
64
61
65
// Utility methods
62
66
@ Override
63
- protected void handleSuccessMessage (String responseBody ) {
64
- super .handleSuccessMessage (responseBody );
67
+ protected void handleMessage (Message msg ) {
68
+ switch (msg .what ){
69
+ case SUCCESS_JSON_MESSAGE :
70
+ handleSuccessJsonMessage (msg .obj );
71
+ break ;
72
+ default :
73
+ super .handleMessage (msg );
74
+ }
75
+ }
76
+
77
+ protected void handleSuccessJsonMessage (Object jsonResponse ) {
78
+ if (jsonResponse instanceof JSONObject ) {
79
+ onSuccess ((JSONObject )jsonResponse );
80
+ } else if (jsonResponse instanceof JSONArray ) {
81
+ onSuccess ((JSONArray )jsonResponse );
82
+ } else {
83
+ onFailure (new JSONException ("Unexpected type " + jsonResponse .getClass ().getName ()));
84
+ }
85
+ }
65
86
87
+ @ Override
88
+ protected void sendSuccessMessage (String responseBody ) {
66
89
try {
67
90
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
- }
91
+ sendMessage (obtainMessage (SUCCESS_JSON_MESSAGE , jsonResponse ));
75
92
} catch (JSONException e ) {
76
- onFailure (e , responseBody );
93
+ sendFailureMessage (e , responseBody );
77
94
}
78
95
}
79
96
0 commit comments