gpt4 book ai didi

android - java.lang.String 无法转换为 java.util.HashMap 异常

转载 作者:行者123 更新时间:2023-11-29 16:13:59 25 4
gpt4 key购买 nike

我喜欢将所选项目值从 ListView 传递到另一个 Activity 。我正在使用具有属性 idCity 和 nameCity 的 City 类,我想将所选城市的值传递给另一个 Activity 此代码抛出 java.lang.ClassCastException: java.lang.String cannot be cast to 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();
}
}

也许有人遇到过同样的问题?

最佳答案

您的数组适配器是一个字符串列表:

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);

关于android - java.lang.String 无法转换为 java.util.HashMap 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10872292/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com