获取listview中所选行的数据

时间:2013-05-13 11:33:47

标签: android android-intent android-listview

我创建了一个应用程序,其中listview从数据库中填充。现在我想要在toast中看到点击的值的详细信息。如何获取所点击行的数据?

下面是我的.java页面..

public class ListviewActivity extends ListActivity{

ListView mListView;
@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.listlayout);
    mListView=(ListView)findViewById(R.id.list);

     DbAdapter dbHelper = new DbAdapter(this);
        dbHelper.open();

        // Get a Cursor for the list items
        Cursor listCursor = dbHelper.fetchListItems();
        startManagingCursor(listCursor);

        // set the custom list adapter
        setListAdapter(new MyListAdapter(this, listCursor));

        mListView = getListView();
        mListView.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view, int position,long id){
                String val=(String)(mListView.getItemAtPosition(position));

                Toast.makeText(ListviewActivity.this,position, Toast.LENGTH_SHORT).show();

            }
        });


}

当我点击一行时,应用程序被强行关闭,并出现以下错误:

E/AndroidRuntime(13011): FATAL EXCEPTION: main
E/AndroidRuntime(13011): java.lang.ClassCastException: android.database.sqlite.SQLiteCursor
E/AndroidRuntime(13011):    at com.android.pickuplistview.ListviewActivity$1.onItemClick(ListviewActivity.java:38)
E/AndroidRuntime(13011):    at android.widget.AdapterView.performItemClick(AdapterView.java:284)
E/AndroidRuntime(13011):    at android.widget.ListView.performItemClick(ListView.java:3382)
E/AndroidRuntime(13011):    at android.widget.AbsListView$PerformClick.run(AbsListView.java:1696)
E/AndroidRuntime(13011):    at android.os.Handler.handleCallback(Handler.java:587)
E/AndroidRuntime(13011):    at android.os.Handler.dispatchMessage(Handler.java:92)
E/AndroidRuntime(13011):    at android.os.Looper.loop(Looper.java:123)
E/AndroidRuntime(13011):    at android.app.ActivityThread.main(ActivityThread.java:4627)
E/AndroidRuntime(13011):    at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime(13011):    at java.lang.reflect.Method.invoke(Method.java:521)
E/AndroidRuntime(13011):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
E/AndroidRuntime(13011):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
E/AndroidRuntime(13011):    at dalvik.system.NativeStart.main(Native Method)

我的数据库适配器页面在这里给出:

public class DbAdapter {
 private static final String DB_NAME = "ListData";
    private static final String TABLE_ITEMS = "itemslist";
    public static final String COL_ID = "_id";
    public static final String COL_ITEMS = "items";
    public static final String COL_NAME = "name";
    public static final String COL_ADDRESS = "address";
    public static final String COL_STATUS="status";

    private static final int DB_VERSION = 1;

    private final Context mCtx;
    private DatabaseHelper mDbHelper;
    private SQLiteDatabase mDb;

    private static final String CREATE_DB_TABLE_DATES = 

        "CREATE TABLE "+TABLE_ITEMS+" ("+ 
            COL_ID +" INTEGER PRIMARY KEY AUTOINCREMENT, "+ 
            COL_ITEMS + " TEXT NOT NULL, " + 
            COL_NAME + " TEXT, " + 
            COL_ADDRESS + " TEXT, " +
            COL_STATUS + " TEXT " +
            ");";

    private static final String CREATE_TEST_DATA1 = 
        "INSERT INTO "+TABLE_ITEMS+
            " ("+
                COL_ITEMS+","+
                COL_NAME+","+
                COL_ADDRESS+","+
                COL_STATUS+
                ") VALUES (" +
                "'Gems',"+
                "'KAJU',"+
                "'Behala',"+
                "'DELIVERED'"+
                ");";

    private static final String CREATE_TEST_DATA2 = 
        "INSERT INTO "+TABLE_ITEMS+
        " ("+
        COL_ITEMS+","+
        COL_NAME+","+
        COL_ADDRESS+","+
        COL_STATUS+
        ") VALUES (" +
        "'Eclairs',"+
        "'BIJU',"+
        "'Joka',"+
        "'PENDING'"+
            ");";

    private static final String CREATE_TEST_DATA3 = 
        "INSERT INTO "+TABLE_ITEMS+
        " ("+
        COL_ITEMS+","+
        COL_NAME+","+
        COL_ADDRESS+","+
        COL_STATUS+
        ") VALUES (" +
        "'Donut',"+
        "'RAJU',"+
        "'Kasba',"+
        "'DELIVERED'"+
            ");";

    private static class DatabaseHelper extends SQLiteOpenHelper {

        DatabaseHelper(Context context) {
            super(context, DB_NAME, null, DB_VERSION);
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            db.execSQL(CREATE_DB_TABLE_DATES);
            db.execSQL(CREATE_TEST_DATA1);
            db.execSQL(CREATE_TEST_DATA2);
            db.execSQL(CREATE_TEST_DATA3);
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

            // if the new version is higher than the old version, 
            // delete existing tables:
            if (newVersion > oldVersion) {
                db.execSQL("DROP TABLE IF EXISTS " + TABLE_ITEMS);
                onCreate(db);
            } else {
                // otherwise, create the database
                onCreate(db);
            }

        }

    }

    /**
     * Constructor - takes the context to allow the database to be
     * opened/created
     * 
     * @param ctx the Context within which to work
     */
    public DbAdapter(Context ctx) {
        this.mCtx = ctx;
    }

    public DbAdapter open() throws SQLException {
        mDbHelper = new DatabaseHelper(mCtx);
        mDb = mDbHelper.getWritableDatabase();
        return this;
    }

    public void close() {
        mDbHelper.close();
    }

    public Cursor fetchListItems() {

        Cursor cursor = 
            mDb.query(TABLE_ITEMS, new String[] 
                      {COL_ID, COL_ITEMS, COL_NAME, COL_ADDRESS, COL_STATUS}, 
                      null, null, null, null, null, null);

        if (cursor != null) {
            cursor.moveToFirst();
        }
        return cursor;
    }

}

2 个答案:

答案 0 :(得分:2)

看起来你正在尝试将Cursor转换为String:

String val=(String)(mListView.getItemAtPosition(position));

至少这是错误导致的:

java.lang.ClassCastException: android.database.sqlite.SQLiteCursor

尝试从Cursor获取数据的String表示,而不是直接将Cursor转换为String。

编辑:

Cursor包含指向存储在数据库中的信息的指针。在不知道数据库结构如何的情况下,我不可能真的为你做这件事。但是,您可以尝试以下格式:

String val = mListView.getItemAtPosition(position).getString(columnIndexInteger);

其中columnIndexInteger是列的整数值。如果你不知道它,但有一个String名称,你可以使用:getColumnIndex()。如果是这种情况,请调整:

Cursor c = (Cursor)mListView.getItemAtPosition(position);
String val = c.getString(c.getColumnIndex(DbAdapter.COL_NAME));

以上行应将val设置为与COL_NAME相关联的数据库记录

答案 1 :(得分:0)

发生此异常是因为您正在将整数值传递给toast massage.Toast需要char序列。所以重新替换你的行

    Toast.makeText(ListviewActivity.this,position, Toast.LENGTH_SHORT).show();

  Toast.makeText(ListviewActivity.this,position+"", Toast.LENGTH_SHORT).show();

点击listView。