我遇到了一个问题:在玩弄SQLite
数据库 &时SimpleCursorAdapter
,我明确地创建了一个带有_id
主键列的表:
public class NoteDbHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "notes_db";
private static final String NOTE_TABLE_NAME = "note";
private static final String NOTE_COL_ID = "_id";
private static final String NOTE_COL_TITLE = "title";
private static final String NOTE_COL_CONTENT = "content";
private static final String NOTE_COL_CREATED = "created";
private static final String NOTE_COL_MODIFIED = "modified";
private static final String[] NOTE_COL_PROJECTION = new String[] {
NOTE_COL_TITLE, NOTE_COL_CONTENT, };
public NoteDbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Create table
@Override
public void onCreate(SQLiteDatabase db) {
String createNoteTableSql = "CREATE TABLE " + NOTE_TABLE_NAME + " ("
+ NOTE_COL_ID + " INTEGER PRIMARY KEY," + NOTE_COL_TITLE
+ " TEXT," + NOTE_COL_CONTENT + " TEXT," + NOTE_COL_CREATED
+ " INTEGER," + NOTE_COL_MODIFIED + " INTEGER" + ");";
db.execSQL(createNoteTableSql);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + NOTE_TABLE_NAME);
// Create tables again
onCreate(db);
}
由于SimpleCursorAdapter
需要一个'Cursor'对象,所以我创建了函数:
public Cursor getAllNotesCursor() {
String selectQuery = "SELECT _id as _id, title, content FROM " + NOTE_TABLE_NAME;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
return cursor;
}
注意,我需要用来SELECT _id as _id
使事情起作用,SELECT _id, title...
不起作用,你知道为什么吗?