【发布时间】:2017-03-31 20:04:24
【问题描述】:
我正在关注关于 Android 中 JSON 的教程。我设法将文件中的 JSON 输出到ListView。但是,我不太明白引用特定项目的工作原理。
这是json文件:
{
"contacts": [
{
"id": "c200",
"name": "Ravi Tamada",
"email": "ravi@gmail.com",
"address": "xx-xx-xxxx,x - street, x - country",
"gender" : "male",
"phone": {
"mobile": "+91 0000000000",
"home": "00 000000",
"office": "00 000000"
}
},
{
"id": "c201",
"name": "Figaro",
"email": "figaro@gmail.com",
"address": "xx-xx-xxxx,x - street, x - country",
"gender" : "male",
"phone": {
"mobile": "+91 0000000000",
"home": "00 000000",
"office": "00 000000"
}
},
{
"id": "c202",
"name": "Johnny Depp",
"email": "johnny_depp@gmail.com",
"address": "xx-xx-xxxx,x - street, x - country",
"gender" : "female",
"phone": {
"mobile": "+91 0000000000",
"home": "00 000000",
"office": "00 000000"
}
}
]
}
第一件事:我怎样才能输出例如只有“性别=男性”的项目?
第二件事:每当我在我的ListView 中按下 Ravi Tamada 时,我怎样才能让它只加载它的移动设备?换句话说,如何设置我按下的项目和应该显示的信息之间的链接,同时考虑到它与按下的项目的关系?
这就是我从 json 中检索项目的方式:
switch (view.getId()){
case R.id.button1:
loadmyjson();
try {
JSONObject jsonObj = new JSONObject(jsonString);
JSONArray letters = jsonObj.getJSONArray("contacts");
for (int i = 0; i < letters.length(); i++){
JSONObject first = letters.getJSONObject(i);
String gender = first.getString("gender");
Log.e("and that means", " " + gender);
if (first.getString("name") == "Figaro"){
where.add(gender);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
Log.e("and that means", " " + where);
break;
}
问题是这个 if 语句总是错误的。
【问题讨论】:
-
第一件事:您应该创建一个与该 Json 具有相同结构的对象。然后你只需要迭代列表并保存属性为“gender”=“male”的列表。第二件事:你必须在你的适配器和你的活动/片段之间创建一个回调。并创建一个 onClickListener 并将其设置为 ViewHolder 内的每个 itemView 作为参数传递您单击的位置或项目本身。
-
谢谢,你能解释一下如何迭代它吗?我试过用 if 语句,但它总是错误的。