我正在尝试将我拥有的 JSON 提要中的内容放入 ListView,使用 Android 异步 Http 客户端处理 HTTP 请求。但是,我认为请求的性质会导致适配器接收一个null
值,而不是我想要的数据数组。
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ApplicationGlobal g = (ApplicationGlobal) getApplication();
boolean userLoggedIn = g.getUserLoggedIn();
AsyncHttpClient clientSession = new AsyncHttpClient();
PersistentCookieStore cookieStore = g.getCookieStore();
clientSession.setCookieStore(cookieStore);
if (!userLoggedIn) {
login();
} else {
ArrayList<HashMap<String, String>> newsFeed = getNewsJson();
// Second to be printed:
System.out.println("LIST DATA");
System.out.println(newsFeed);
SimpleAdapter adapter = new SimpleAdapter(
this,
newsFeed,
R.layout.assignment_list_row_view,
new String[] { "photo", "dateAssigned", "dateDue",
"description" },
new int[] { R.id.text1, R.id.text2, R.id.text3, R.id.text4 });
setListAdapter(adapter);
}
}
ArrayList<HashMap<String, String>> newsFeed = new ArrayList<HashMap<String, String>>();
private ArrayList<HashMap<String, String>> getNewsJson() {
ApplicationGlobal g = (ApplicationGlobal) getApplication();
AsyncHttpClient clientSession = new AsyncHttpClient();
PersistentCookieStore cookieStore = g.getCookieStore();
clientSession.setCookieStore(cookieStore);
clientSession.get("http://192.168.1.42:5000/news/dummy/all/",
new JsonHttpResponseHandler() {
@Override
public void onSuccess(JSONObject response) {
JSONArray assignments = new JSONArray();
try {
assignments = response.getJSONArray("assignments");
JSONObject c = assignments.getJSONObject(0);
for (int i = 0; i < assignments.length() + 1; i++) {
JSONObject individualAssignment = new JSONObject(
c.getString(Integer.toString(i)));
HashMap<String, String> map = new HashMap<String, String>();
map.put("photo",
individualAssignment.getString("photo"));
map.put("dateAssigned", individualAssignment
.getString("date_assigned"));
map.put("dateDue", individualAssignment
.getString("date_due"));
map.put("description", individualAssignment
.getString("description"));
newsFeed.add(map);
// Last to be printed (and printed multiple times, as expected)
System.out.println("RAW DATA");
System.out.println(newsFeed);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
// First to be printed:
System.out.println("RETURNED DATA");
System.out.println(newsFeed);
return newsFeed;
}
我认为正在发生的事情,如上面三个放置的评论所示,onSuccess()
是没有足够快地调用数据以将数据传递给具有非空值的适配器。
重新设计此代码片段以使其正常工作的最佳方法是什么?