1

我正在尝试从 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)
4

1 回答 1

1

这是因为您将 Cursor 传递给 ListView 并转换 String 而不是 Cursor。但是,我坚持不要将 Cursor 传递给 ListView,而是您可以从某个 Collection 中的 Cursor 获取数据,也许是 ArrayList,然后将 ArrayList 传递给 ListView 的适配器。

于 2012-12-18T17:13:28.363 回答