我的数据库中有一些测试值,我想在android中获取它们。 这是我的数据库中的值的以下JSON输出:
[{"email_address":"rainier_gaari@hotmail.com","comment":"qwehgashdgaskdaweq","date_comment":"2014-06-21","time_comment":"08:28:00","password":"rainier1990"},
{"email_address":"rainier_gaari@hotmail.com","comment":"asfasdasdasd","date_comment":"2104-06-12","time_comment":"09:03:00","password":"rainier1990"}
{"email_address":"rainier_gaari@hotmail.com","comment":"asdsfafd","date_comment":"2014-06-22","time_comment":"04:44:00","password":"rainier1990"}]
但是每次我运行这段代码:http://prntscr.com/3vhs5j时,它只给出了JSON输出的第一行:http://prntscr.com/3vi34b
如何在android中显示所有行(而不是1行)?
答案 0 :(得分:0)
如果你把一些代码放在你的问题中来获取JSON,以便更容易引用它会有所帮助,但是,我没有看到循环,这就是它只获得第一行的原因。
您可能想要引用这个问题:JSON Array iteration in Android/Java但基本上使用JSONArray的length
属性并循环多次。
答案 1 :(得分:0)
您可以使用android API提供的JSONObject。 JSONObject有一个名为getJSONArray()
的方法http://developer.android.com/reference/org/json/JSONObject.html#getJSONArray(java.lang.String)
您的错误是您正在使用您的Object实例化JSONArray。你应该试试这个:
JSONArray myArray =jsonObject.getJSONArray();
这是我的一个应用程序的代码片段,可以很好地检索Json数据。
success = jObject.getInt(TAG_SUCCESS);
vehicles = jObject.getJSONArray(Vehicle.TAG_VEHICLES);
if(success == 1) {
// loop through all the vehicles
for(int i = 0; i < vehicles.length(); i++) {
JSONObject obj = vehicles.getJSONObject(i);
// Get each element based on it's tag
String year = obj.getString(Vehicle.TAG_YEAR);
String model = obj.getString(Vehicle.TAG_MODEL);
String brand = obj.getString(Vehicle.TAG_BRAND);
String color = obj.getString(Vehicle.TAG_COLOR);
String license_plate = obj.getString(Vehicle.TAG_LICENSE);
String main_driver = obj.getString(Vehicle.TAG_DRIVER);
String policeNumber = obj.getString(Vehicle.TAG_POLICENUMBER);
String driversLicense = obj.getString(Vehicle.TAG_DRIVER_LICENSE);
String licenseState = obj.getString(Vehicle.TAG_LICENSE_STATE);
String driverBirthday = obj.getString(Vehicle.TAG_BIRTHDAY_MONTH) + "/" +
obj.getString(Vehicle.TAG_BIRTHDAY_DAY) + "/" +
obj.get(Vehicle.TAG_BIRTHDAY_YEAR);
String driverGender = obj.getString(Vehicle.TAG_DRIVER_GENDER);
ListRowGroup group = new ListRowGroup(brand + " " + year + " " + model, brand);
group.children.add(brand + " " + year + " " + model);
group.children.add(policeNumber);
group.children.add(model);
group.children.add(color);
group.children.add(license_plate);
group.children.add(main_driver);
group.children.add(driversLicense + " - " + licenseState);
group.children.add(driverBirthday + " - " + driverGender);
vehiclesGroup.append(i, group);
}