0

我有一个从数据库中填充的微调器女巫,当我选择一个项目时,我想在数据库中返回该项目的行 ID(主键);这是我的代码:

private int getcategoryrowid(Spinner spinner){                  

        AndroidOpenDbHelper openHelperClass = new AndroidOpenDbHelper(this);

        // Then we need to get a readable database
        SQLiteDatabase sqliteDatabase = openHelperClass.getReadableDatabase();


        //
        Cursor cursor1 = (Cursor) (spinner.getSelectedItem());
        String t=String.valueOf(spinner.getSelectedItem());
        System.out.println(t);
        int rowid = cursor1.getInt(cursor1.getColumnIndex("_id"));
        System.out.println(rowid);
         cursor1.close();
         sqliteDatabase.close();
        return rowid;

}

这是logcat:

06-14 16:02:01.840: W/dalvikvm(14081): threadid=1: thread exiting with uncaught exception (group=0x40015560)
06-14 16:02:01.880: E/AndroidRuntime(14081): FATAL EXCEPTION: main
06-14 16:02:01.880: E/AndroidRuntime(14081): java.lang.ClassCastException: java.lang.String
06-14 16:02:01.880: E/AndroidRuntime(14081):    at com.app.pfe.Addfile.getcategoryrowid(Addfile.java:345)
06-14 16:02:01.880: E/AndroidRuntime(14081):    at com.app.pfe.Addfile.onClick(Addfile.java:85)
06-14 16:02:01.880: E/AndroidRuntime(14081):    at android.view.View.performClick(View.java:2485)
06-14 16:02:01.880: E/AndroidRuntime(14081):    at android.view.View$PerformClick.run(View.java:9080)
06-14 16:02:01.880: E/AndroidRuntime(14081):    at android.os.Handler.handleCallback(Handler.java:587)
06-14 16:02:01.880: E/AndroidRuntime(14081):    at android.os.Handler.dispatchMessage(Handler.java:92)
06-14 16:02:01.880: E/AndroidRuntime(14081):    at android.os.Looper.loop(Looper.java:123)
06-14 16:02:01.880: E/AndroidRuntime(14081):    at android.app.ActivityThread.main(ActivityThread.java:3683)
06-14 16:02:01.880: E/AndroidRuntime(14081):    at java.lang.reflect.Method.invokeNative(Native Method)
06-14 16:02:01.880: E/AndroidRuntime(14081):    at java.lang.reflect.Method.invoke(Method.java:507)
06-14 16:02:01.880: E/AndroidRuntime(14081):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
06-14 16:02:01.880: E/AndroidRuntime(14081):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
06-14 16:02:01.880: E/AndroidRuntime(14081):    at dalvik.system.NativeStart.main(Native Method)

我的代码有什么问题?

4

2 回答 2

1

为什么要有一个完全独立的班级?您可以从onItemSelected方法中获取它,因为它在传入的参数中提供给您(它是long id部分)......

spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
    @Override
    public void onNothingSelected(AdapterView<?> parent) {
    }
    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
            long rowId = id;    
    }
});
于 2012-06-14T16:33:27.990 回答
1

在顶部创建 Activity 的上下文

public Context cntx = this;

现在添加cntx如下:

AndroidOpenDbHelper openHelperClass = new AndroidOpenDbHelper(cntx);
于 2012-06-14T16:54:31.260 回答