我必须读取json文件,两个字段:name和id_name。我创建了一个数组列表。用户只能看到名称。当用户点击名称时,我必须获得 ID 。我只向您介绍AssyncTask doInBackground过程的一部分。另外我用两个参数name和id创建了类名。
请帮帮我。这是我的代码。
protected ArrayList<Name> doInBackground(String... params) {
ArrayList<Name> nameList = new ArrayList<>();
String result = "";
......
for (int i = 0; i < rootArray.length(); i++) {
JSONObject nameObject = rootArray.getJSONObject(i);
String name = nameObject.getString("name");
String id = nameObject.getString("id_name");
nameList.add(new NAME(name, id));
}
return nameList;
}
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String my_id = adapter.getItem(position).toString();
}
});
非常感谢。
答案 0 :(得分:1)
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TextView tv_ID=(TextView)view.findViewById(R.id.tv_id);//Check your xml and set proper ID
String my_id =tv_ID.getText().toString();
Toast.makeText(CurrentActivity.this, my_id , Toast.LENGTH_SHORT).show();
}
});
答案 1 :(得分:0)
为此活动声明您的数组全局,如
ArrayList<Name> nameList = new ArrayList<>();
然后
protected ArrayList<Name> doInBackground(String... params) {
String result = "";
......
if(nameList != null)
nameList.clear();
for (int i = 0; i < rootArray.length(); i++) {
JSONObject nameObject = rootArray.getJSONObject(i);
String name = nameObject.getString("name");
String id = nameObject.getString("id_name");
nameList.add(new NAME(name, id));
}
return nameList;
}
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Name name = nameList.get(position);
String id = name.getId();
String id = name.getName();
}
});
注意:如果您没有名称模型的getter方法,请创建getter方法。
答案 2 :(得分:0)
尝试 ListView.get(位置); 代替 Adapter.get(位置);