我喜欢将ListView中的选定项值传递给另一个activity.I我正在使用带有属性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();
}
}
也许有人有同样的问题?
答案 0 :(得分:4)
您的数组适配器是字符串列表:
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, c);
getItemAtPosition(int position)
将返回与Object
类型匹配的Adapter
。因此,在这种情况下,它将返回一个字符串,但您正在尝试将其强制转换为HashMap<String, String>
HashMap<String,String> map=(HashMap<String, String>) parent.getItemAtPosition(position);
将其更改为:
String result = (String) parent.getItemAtPosition(position);