我有一个 JSON 字符串,我正在尝试解析然后进入 ListView,我的代码没有抛出任何错误,但它也不起作用,我无法确定我可能出错的地方。以下是我的代码:
protected void onPostExecute(String result) {
super.onPostExecute(result);
str = result;
Toast.makeText(getApplicationContext(),""+str, Toast.LENGTH_LONG).show(); // Able to toast the JSON string (str) here.
mylist = new ArrayList<HashMap<String, String>>();
map = new HashMap<String, String>();
try {
JSONArray jArray = new JSONArray(str);
for (int i = 0; i < jArray.length(); i++) {
JSONObject jObject = jArray.getJSONObject(i);
j_id = jObject.getString(ID);
j_make = jObject.getString(MAKE);
j_model = jObject.getString(MODEL);
j_version = jObject.getString(VERSION);
j_price = jObject.getString(PRICE);
j_reg_plc = jObject.getString(PLACE_REG);
Toast.makeText(getApplicationContext(),"After assign", Toast.LENGTH_LONG).show();
data = "Make: "+ j_make + "\nModel: " + j_model + "\nVersion: " + j_version + "\nPrice: " + j_price
+ "\nCity: " + j_reg_plc;
map.put("car", data);
mylist.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
// list = (ListView) findViewById(R.id.listView1);
Toast.makeText(getApplicationContext(),""+mylist, Toast.LENGTH_LONG).show();
String[] from = new String[] { "car"};
int[] to = new int[] { R.id.text1 };
ListAdapter adapt = new SimpleAdapter(view_cars.this, mylist,R.layout.text_adaptr, from, to);
list.setAdapter(adapt);
}
似乎我的 for 循环突然退出,它没有被执行两次,因为我从网络接收的数组的长度是 2。我附上了我得到的 JSON 数组的屏幕截图
有关详细信息,请检查代码以获取注释。