我喜欢将所选项目值从 ListView 传递给另一个活动。我正在使用具有 idCity 和 nameCity 属性的 City 类,我喜欢将所选城市的值传递给另一个活动 此代码正在抛出 java.lang.ClassCastException: java .lang.String 不能转换为 java.util.HashMap
public ListView cities;
ArrayList<City> cityList=new ArrayList<City>();
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.cities_view);
Resources r = getResources();
String[] c = r.getStringArray(R.array.cities);
for(int i=0;i<c.length;i++)
{
cityList.add(new City(i,c[i]));
}
for(int i=0;i<c.length;i++)
{
System.out.println(cityList.get(i).idCity);
System.out.println(cityList.get(i).nameCity);
}
cities = (ListView) findViewById(R.id.listCities);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, c);
cities.setAdapter(adapter);
File file = new File(Environment.getExternalStorageDirectory()
.getAbsolutePath(), getString(R.string.exchangeOfficesFile));
if (!file.exists()) {
startService(new Intent(this, DownloadAsyncService.class));
}
try{
List<Map<String, String>> data = new ArrayList<Map<String, String>>();
for (City c : cityList) {
Map<String, String> map = new HashMap<String, String>(2);
map.put("idCity", Integer.toString(c.getIdCity()));
map.put("nameCity", c.getNameCity());
data.add(map);
}
cities.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent intent = new Intent(getApplicationContext(),
CitiesDetails.class);
HashMap<String,String> map=(HashMap<String, String>) parent.getItemAtPosition(position);
intent.putExtra("idCity", map.get("idCity"));
intent.putExtra("nameCity", map.get("nameCity"));
startActivity(intent);
}
});
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
也许有人有同样的问题?