我在android上使用listview,下面的代码在点击另一个新活动的列表项后给出了错误
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting list view size
int size = parent.getCount();
// initializing array according to list view size
String[] all_pid = new String[size];
String[] all_name = new String[size];
String[] all_address = new String[size];
String[] all_latitude = new String[size];
String[] all_longitude = new String[size];
// looping data into array according to getItemAtPosition
for (int i = 0; i < size; i++) {
HashMap<String, String> extractor = (HashMap<String, String>) parent.getItemAtPosition(i);
// fill data into array
all_pid[i] = extractor.get("pid");
all_name[i] = extractor.get("name");
all_address[i] = extractor.get("address");
all_latitude[i] = extractor.get("latitude");
all_longitude[i]=extractor.get("longitude");
}
Intent in = new Intent(getApplicationContext(),SingleContactActivityMainFragment.class);
in.putExtra("APid", all_pid);
in.putExtra("AName", all_name);
in.putExtra("AAddress", all_address);
in.putExtra("ALatitude", all_latitude);
in.putExtra("ALongitude", all_longitude);
// added size for initial view pager initialization
in.putExtra("size", size);
in.putExtra("QUOTES", position);
Log.v(DEBUG, "position Passed: " + position);
startActivity(in);
}
显示的错误是:
05-27 15:30:12.985: E/AndroidRuntime(23905): java.lang.ClassCastException: java.lang.Integer cannot be cast to java.util.HashMap
05-27 15:30:12.985: E/AndroidRuntime(23905): at com.example.fightvaw.jsontest.MainActivity$4.onItemClick(MainActivity.java:226)
如何解决这些类型的错误?
答案 0 :(得分:1)
这是我的自定义适配器上的先前代码:
@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return (position);
}
这解决了我的自定义适配器中的代码:
@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return data.get(position);
}
其中data
被定义为ArrayList<HashMap<String, String>> data;
答案 1 :(得分:0)
这一行
HashMap<String, String> extractor = (HashMap<String, String>) parent.getItemAtPosition(i);
导致你的崩溃。 parent
是一个AdapterView,如果您调用getItemAtPosition(i)
,则返回一个Integer。
您可以将parent
替换为ListAdapter(您需要填充ListView)来解决此问题。之后您的代码应如下所示:
HashMap<String, String> extractor = youListAdapter.get(i);
答案 2 :(得分:0)
您的父AdapterView
设计用于保存int
值,它们会自动加到Integer
。这就是为什么通过致电parent.getItemAtPosition(i)
获得Integer
。显然,Integer
无法投放到HashMap