如何在SQLite android数据库中搜索特定ID并返回其对象

时间:2015-09-06 17:14:45

标签: android sqlite

我想在myDBHandler中添加一个方法,该方法通过ID搜索它所属的行,然后创建一个类的新实例,并在构造函数中设置所有信息,如名称,Id和图像。

那么如何获取行的位置并用列填充我的构造函数?

谢谢!

1 个答案:

答案 0 :(得分:3)

public MyObject getById(String id) {
    SQLiteDatabase db = getReadableDatabase();
    String where = COLUMN_SEARCHID + " = ?";
    String[] whereArgs = {id};
    Cursor cursor = db.query(TABLE_GAMES, null, where, whereArgs, null);
    MyObject obj = null;
    try {
        if (cursor.moveToFirst()) {
            // read column data
            obj = new MyObject(...);
        }
    } finally {
        cursor.close();
    }
    return obj;
}