1

我喜欢将所选项目值从 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();
}
}

也许有人有同样的问题?

4

1 回答 1

4

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

ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, c);

getItemAtPosition(int position)将返回一个ObjectAdapter. 所以在这种情况下它会返回一个字符串,但你正试图将它转换为HashMap<String, String>

HashMap<String,String> map=(HashMap<String, String>) parent.getItemAtPosition(position);

将其更改为:

String result = (String) parent.getItemAtPosition(position);
于 2012-06-03T17:20:10.807 回答