我在这里有另一个问题。我发布了我的AsyncTask函数中的代码,以从JSONObject(webservice)获取值。我的问题是我有一个List,我用onSuccess方法中的json数据填充此列表,但后来,在AsyncTask的onPostExecute方法中,“result”为null。
private class getCategories extends AsyncTask<String, Void, List<Category>> {
private int num_cat_subcat; // category count
@Override
protected List<Category> doInBackground(String... arg0) {
AsyncHttpClient client = new AsyncHttpClient();
client.get(arg0[0], null, new JsonHttpResponseHandler() {
public void onSuccess(JSONObject data) {
try {
JSONObject response = data.getJSONObject("response");
JSONArray categories = response
.getJSONArray("categories");
// elements count
num_cat_subcat = categories.length();
for (int i = 0; i < categories.length(); i++) {
JSONObject item = (JSONObject) categories
.getJSONObject(i);
if (item.getString("id").equalsIgnoreCase(
"4d4b7105d754a06376d81259")) {
JSONArray subcategories = item
.getJSONArray("categories");
// Category --> id, name, pluralName, shortName,
// icon_prefix, icon_suffix, primary, parentId
Category newItem = new Category(item
.getString("id"), item
.getString("name"), item
.getString("pluralName"), item
.getString("shortName"), null, null,
null);
listCategories.add(newItem);
newItem = null;
if (subcategories.length() > 0) {
// Si tiene subcategorias las contamos.
num_cat_subcat += subcategories.length();
for (int j = 0; j < subcategories.length(); j++) {
JSONObject subitem = (JSONObject) subcategories
.getJSONObject(j);
Category newSubItem = new Category(
subitem.getString("id"),
subitem.getString("name"),
subitem.getString("pluralName"),
subitem.getString("shortName"),
null, null, item
.getString("id"));
listCategories.add(newSubItem);
newSubItem = null;
}
}
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void onFailure(Throwable arg0) {
}
});
return listCategories;
}
@Override
protected void onPostExecute(List<Category> result) {
Log.i("result", result.toString());
for (int k = 0; k < result.size(); k++) {
ALLOFTHEM += result.get(k).getId();
if (k < result.size() - 1) {
ALLOFTHEM += ",";
}
}
}
}
答案 0 :(得分:3)
如果您使用loopj android-async-http,则无需使用AsyncTask
从服务器doInBackground
获取数据并更新onPostExecute中的UI,因为onSuccess
方法始终在UI线程上执行背景计算。只需要将AsyncTask作为:
AsyncHttpClient client = new AsyncHttpClient();
client.get("Pass Url Here", null, new JsonHttpResponseHandler() {
@Override
public void onSuccess(JSONObject data) {
// update your ListView here
}
@Override
public void onFailure(Throwable arg0, JSONObject arg1) {
// TODO Auto-generated method stub
super.onFailure(arg0, arg1);
}
});
答案 1 :(得分:2)
onPostExecuted
用完它时,会调用 doInBackground
。如果AsyncHttpClient
的get方法不是阻塞方法,则在onPostExecuted
解析结果之前调用onSuccess
答案 2 :(得分:0)
onPostExecuted,因此尝试在循环中显示某些内容或调试该代码。
Log.e("Test", item.getString("id"));//inside for Loop
并且在你的for循环之前使用它
listCategories = new List<Category>();
希望有所帮助。