我正在尝试从JSONArray中显示Android中的项目ListView,如下所示
{"myArray":[{"id":"816","name":"Shopping","uid":"20"},{"id":"817","name":"Grocery","uid":"20"},{"id":"818","name":"Entertainment","uid":"20"},{"id":"819","name":"Maid\/Driver","uid":"20"}]}
我想在Listview中显示这些内容,如下所示
816 Shopping 20
817 Grocery 20
818 Environment 20
819 Maid\/Driver 20
这是我正在处理的java代码
JSONArray the_json_array = jObj.getJSONArray("myArray");
List<String> list = new ArrayList<String>();
for (int i=0; i<the_json_array.length(); i++) {
list.add( the_json_array.getString(i) );
}
String[] stringArray = list.toArray(new String[list.size()]);
final ArrayAdapter adapter = new ArrayAdapter<String>(TransactionCategory.this,android.R.layout.simple_list_item_1,stringArray);
ListView listView = (ListView) findViewById(R.id.listView2);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// my actions on list items
}
});
我遇到for循环的问题
我只需要为ListView中的每个项目获取值。
答案 0 :(得分:0)
尝试使用Gson解析json,如下面的代码所示:
public class Item {
@SerializedName("id")
private String id;
@SerializedName("name")
private String name;
@SerializedName("uid")
private String uid;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
@Override
public String toString() {
return id + " " + name + " " + uid;
}
}
public class ItemList {
@SerializedName("myArray")
private List<Item> items;
public List<Item> getItems() {
if (items == null) {
items = new ArrayList<>();
}
return items;
}
}
然后更改您的代码:
...
Gson gson = new Gson();
ItemList itemList = gson.fromJson(jObj, ItemList.class);
final ArrayAdapter adapter = new ArrayAdapter<Item>(TransactionCategory.this,android.R.layout.simple_list_item_1, itemList.getItems());
ListView listView = (ListView) findViewById(R.id.listView2);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// my actions on list items
}
}
...