我在 Android 中使用 Sqlite 并从数据库中获取值,我使用如下方法:
Cursor cursor = sqliteDatabase.rawQuery("select title,category from table", null);
int columnIndexTitle = cursor.getColumnIndex("title");
iny columnIndexCategory = cursor.getColumnIndex("category");
cursor.moveToFirst();
while (cursor.moveToNext()) {
String title = cursor.getString(columnIndexTitle);
String category = cursor.getString(columnIndexCategory);
}
cursor.close();
我想创建自己的 Cursor,这样我就可以使用一种方法执行 getColumnIndex()
和 getString()
。像这样:
String title = cursor.getString("title");
我想创建自己的类来扩展我从 sqliteDatabase.rawQuery
获得的游标,但我不确定如何完成此操作。我应该扩展 SQLiteCursor 还是应该怎么做?这有可能吗?这是个好主意吗?
最佳答案
我在寻找创建自定义 Cursor
以与 SQLiteDatabase
一起使用的最佳方法时遇到了这个问题。在我的例子中,我需要 Cursor 的一个额外属性来携带一条额外的信息,所以我的用例与问题正文中的不完全一样。发布我的发现,希望对您有所帮助。
对我来说棘手的部分是 SQLiteDatabase 查询方法返回一个 Cursor,我需要将自定义子类传递给 Cursor。
我在 Android API 中找到了解决方案:使用 CursorWrapper类(class)。它似乎正是为此而设计的。
类(class):
public class MyCustomCursor extends CursorWrapper {
public MyCustomCursor(Cursor cursor) {
super(cursor);
}
private int myAddedAttribute;
public int getMyAddedAttribute() {
return myAddedAttribute;
}
public void setMyAddedAttribute(int myAddedAttribute) {
this.myAddedAttribute = myAddedAttribute;
}
}
用法:
public MyCustomCursor getCursor(...) {
SQLiteDatabase DB = ...;
Cursor rawCursor = DB.query(...);
MyCustomCursor myCursor = new MyCustomCursor(rawCursor);
myCursor.setMyAddedAttribute(...);
return myCursor;
}
关于Android:如何创建我自己的游标类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5639856/