我试图从listview获取项目的值,但是当我尝试“adapter.getItem(position)”时,我收到了一个强制转换错误。
我假设getItem函数是发生错误的地方,根据日志,但我不确定我怎么能将值传递给字符串?
相关代码是:
public String getItem(int pos) {
String myString = (String) adapter.getItem(pos);
return myString;
}
private OnItemClickListener onAnswerClicked = new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String getValue = getItem(position);
Toast.makeText(getApplicationContext(),
"Click ListItem Number " + getValue, Toast.LENGTH_LONG)
.show();
}
};
我在logcat中收到的错误是:
12-18 10:50:02.314: E/AndroidRuntime(18988): FATAL EXCEPTION: main
12-18 10:50:02.314: E/AndroidRuntime(18988): java.lang.ClassCastException: android.database.sqlite.SQLiteCursor cannot be cast to java.lang.String
12-18 10:50:02.314: E/AndroidRuntime(18988): at com.sembasys.metrosleepnyc.ChooseRoute.getItem(ChooseRoute.java:61)
12-18 10:50:02.314: E/AndroidRuntime(18988): at com.sembasys.metrosleepnyc.ChooseRoute$1.onItemClick(ChooseRoute.java:72)
12-18 10:50:02.314: E/AndroidRuntime(18988): at android.widget.AdapterView.performItemClick(AdapterView.java:298)
12-18 10:50:02.314: E/AndroidRuntime(18988): at android.widget.AbsListView.performItemClick(AbsListView.java:1100)
12-18 10:50:02.314: E/AndroidRuntime(18988): at android.widget.AbsListView$PerformClick.run(AbsListView.java:2749)
12-18 10:50:02.314: E/AndroidRuntime(18988): at android.widget.AbsListView$1.run(AbsListView.java:3423)
12-18 10:50:02.314: E/AndroidRuntime(18988): at android.os.Handler.handleCallback(Handler.java:725)
12-18 10:50:02.314: E/AndroidRuntime(18988): at android.os.Handler.dispatchMessage(Handler.java:92)
12-18 10:50:02.314: E/AndroidRuntime(18988): at android.os.Looper.loop(Looper.java:137)
12-18 10:50:02.314: E/AndroidRuntime(18988): at android.app.ActivityThread.main(ActivityThread.java:5039)
12-18 10:50:02.314: E/AndroidRuntime(18988): at java.lang.reflect.Method.invokeNative(Native Method)
12-18 10:50:02.314: E/AndroidRuntime(18988): at java.lang.reflect.Method.invoke(Method.java:511)
12-18 10:50:02.314: E/AndroidRuntime(18988): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
12-18 10:50:02.314: E/AndroidRuntime(18988): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
12-18 10:50:02.314: E/AndroidRuntime(18988): at dalvik.system.NativeStart.main(Native Method)
答案 0 :(得分:1)
这是因为你将Cursor传递给ListView并转换String而不是Cursor。但是,我坚持不将Cursor传递给ListView,而是可以从某些Collection可能的ArrayList中的Cursor获取数据,然后将ArrayList传递给ListView的适配器。