【发布时间】:2014-09-03 01:38:06
【问题描述】:
我有 APIHelper 类,其静态方法异步向服务器发出请求,接收 json 字符串,解析并返回 Object 或 ArrayList:
...
public static ArrayList<Item> getItemsInCategory(int id_category) throws ExecutionException, InterruptedException, JSONException {
DoRequest doRequest = new DoRequest();
String jsonString = doRequest.execute(API_PATH + PRODUCT_SEARCH + CATEGORY_ID + id_category).get();
JSONObject jsonObject = new JSONObject(jsonString);
JSONArray jsonArray = jsonObject.getJSONArray("products");
return Item.fromJson(jsonArray);
}
public static Item getItem(int id_item) throws ExecutionException, InterruptedException, JSONException {
DoRequest doRequest = new DoRequest();
String jsonString = doRequest.execute(API_PATH + PRODUCT_GET_INFO + id_item).get();
JSONObject jsonObject = new JSONObject(jsonString);
return Item.fromJson(jsonObject);
}
...
现在我想在不调用 AsyncTask 类 DoRequest 中的 get() 方法的情况下创建方法。
我的 DoRequest 类:
public class DoRequest extends AsyncTask<String, Void, String> {
ResultListener mResultListener;
public abstract interface ResultListener{
Object onResultAvailable(String result) throws JSONException;
}
DoRequest(ResultListener resultListener){
mResultListener = resultListener;
}
@Override
protected String doInBackground(String... URL) {
ServiceHandler serviceHandler = new ServiceHandler();
String jsonStr = serviceHandler.makeServiceCall(URL[0]);
return jsonStr;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
mResultListener.onResultAvailable(result);
} catch (JSONException e) {
e.printStackTrace();
}
}
帮我更改 APIHelper 类中的方法,它们在 DoRequest 回调后返回值。
【问题讨论】:
标签: java android android-asynctask asynccallback