我有一个ListView
我在显示从JSON格式的网址中获取的ArrayList
中的项目。每个项目由5个元素组成。我想在单击另一个活动时传递与该特定列表项关联的元素。但是当我将ArrayList
传递给另一个活动并迭代ArrayList
时,无论我点击哪个列表项,列表中的最后一项都会打开。
这是我的代码:
MainActivity.java
JSONArray jObject = new JSONArray(responseBody);
for (int i = 0; i < jObject.length(); i++) {
JSONObject menuObject = jObject.getJSONObject(i);
String title= menuObject.getString("Title");
String description= menuObject.getString("BodyText");
String thumbnail= menuObject.getString("ThumbnailPath");
String nUrl = menuObject.getString("Url");
String body = menuObject.getString("Body");
String nBigImage = menuObject.getString("ImageBlobUrls");
map = new HashMap<String,String>();
map.put(SOURCETITLE, title);
map.put(TITLE, description);
map.put(THUMBNAILPATH, thumbnail);
map.put(BODY, body);
map.put(URL, nUrl);
map.put(IMAGEBLOBURLS,nBigImage);
myList.add(map);
}
myListView.setAdapter(itemsAdapter);
myListView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3)
{
// TODO Auto-generated method stub
Intent nIntent = new Intent(Home.this,NDetails.class);
nIntent.putExtra("myItems", myList);
startActivity(nIntent);
}
});
NDetails.java
Intent in = getIntent();
data = (ArrayList<HashMap<String, String>>) in.getSerializableExtra("myItems");
for(Map<String, String> newItem:data)
{
newUrl = newItem.get(Home.URL);
newTitle =newItem.get(Home.SOURCETITLE);
newBody= newItem.get(Home.BODY);
newImage = newItem.get(Home.THUMBNAILPATH);
}
txtNewsTitle.setText(newTitle);
txtNewsBody.setText(newBody);
我该如何解决这个问题? 感谢
答案 0 :(得分:0)
试试这个:
myListView.setOnItemClickListener(new OnItemClickListener()
{
@Override
public void onItemClick(AdapterView<?> arg0,
View arg1, int position, long arg3)
{
// TODO Auto-generated method stub
HashMap myMap = myList.get(position);
Intent nIntent = new Intent(Home.this,NDetails.class);
newsIntent.putExtra("myItems", myMap);
startActivity(nIntent);
}
});
并在另一个活动中获取地图:
data = (HashMap<String, String>>) in.getSerializableExtra("myItems");
newUrl = data.get(Home.URL);
data =newItem.get(Home.SOURCETITLE);
data= newItem.get(Home.BODY);
data = newItem.get(Home.THUMBNAILPATH);
答案 1 :(得分:0)
myListView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
HashMap<String, String> item = ( HashMap<String, String>)arg0.getItemAtPosition(position);
Intent nIntent = new Intent(Home.this,NDetails.class);
newsIntent.putExtra("myItems", myList);
startActivity(nIntent);
}
});
您可以使用AdapterView.getItemAtPosition(int)
检索位置