尝试使用JSON中的数据创建列表视图。下面的phonelist decalred保存从json解析的数据。
ArrayList<HashMap<String, String>> phonelist = new ArrayList<HashMap<String, String>>();
我在片段的onCreateView中执行此操作
for (int i = 0; i < phone.length(); i++) {
try {
JSONObject c = phone.getJSONObject(i);
String phId = c.getString("ph_id");
String phNo = c.getString("ph_no");
HashMap<String, String> map = new HashMap<String, String>();
map.put("ph_id", phId);
map.put("ph_no", phNo);
phonelist.add(map);
} catch (JSONException e) {
e.printStackTrace();
}
}
ListView list = (ListView) rootView.findViewById(R.id.listview1);
ListAdapter adapter = new SimpleAdapter(getActivity(), phonelist,
R.layout.list_item_phone,
new String[]{"ph_id", "ph_no"}, new int[]{
R.id.txtPhoneID, R.id.txtPhoneNum});
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
//TODO
}
});
phonelist 正在从json填充,这是其内容
[{ph_id=1, ph_no=0120-2550000}, {ph_id=2, ph_no=1860-180-3474}, {ph_id=3, ph_no=0120-4698114}, {ph_id=4, ph_no=0361-2525256}, {ph_id=5, ph_no=033-2525368}, {ph_id=6, ph_no=011-25252525}, {ph_id=7, ph_no=0361-2525257}, {ph_id=8, ph_no=033-2525369}, {ph_id=9, ph_no=011-25252526}, {ph_id=10, ph_no=0361-2525258}, {ph_id=11, ph_no=033-2525370}, {ph_id=12, ph_no=011-25252527}]
For some reason though, only the first item shows up in the listview.
编辑:
电话变量声明
JSONArray phone = null;
然后我就像下面那样获得它的价值
phone = ((JSonArrayParser) getArguments().getParcelable("phoneJsonArray")).getJsonArray();
phone.length显示正确的值(12)
答案 0 :(得分:0)
HashMap 被指定为键和值。搜索文本&#34; put(K键,V值)&#34;以供参考。在您的代码中:
map.put("ph_id", phId);
map.put("ph_no", phNo);
我可以看到只有2个键被添加到此地图对象中,即使您从JSON添加了大量数据。
作为建议,而不是文字字符串&#34; ph_id&#34;作为关键,您可以将变量 phId作为键,而v alue可以是phNo 。这可以是一个代码设计。
如果你也发布了SimpleAdapter,也许这是一个好主意,特别是在getView()中。