我正在做我的第一個android項目。其目的是在數據庫中存儲按鈕被按下時的時間。然後使用LoaderManager/CursorLoader/Custom SimpleCursorAdapter/ContentProvider/ListView活動顯示數據庫的全部內容。爲什麼我的sqlite數據庫中的_id列爲空?
問題是這樣的:當我插入一個新行時,數據庫沒有在_id列中存儲任何數字。它只是空白:
我試圖找到一個答案,這無濟於事,我試圖深入調試寫入數據庫代碼,無濟於事。
當按下按鈕時執行的代碼是:
// Function to record an awake time
public void onAwake(View view) {
DateTime now = new DateTime();
DateTime startOfCurrentDay = now.withTimeAtStartOfDay();
DateTime noonOfCurrentDay = startOfCurrentDay.plusHours(12);
TimeEntry timeEntry = new TimeEntry(noonOfCurrentDay.getMillis(), now.getMillis(), TimeEntry.TimeEntryType.TIME_RECORD, TimeEntry.Direction.WAKE);
TimeEntryDbHandler timeEntryDbHandler = new TimeEntryDbHandler(this);
long id = timeEntryDbHandler.addTimeEntry(timeEntry);
// Notify user of execution
Toast.makeText(this, R.string.toast_awake + " ID:" + String.valueOf(id), Toast.LENGTH_SHORT).show();
}
當此執行中,在烤麪包示出的ID被遞增你所期望的(目前爲32或東西)。
數據庫處理程序代碼是計算方式如下:
public class TimeEntryDbHandler extends SQLiteOpenHelper implements BaseColumns {
// If you change the database schema, you must increment the database version.
public static final int DATABASE_VERSION = 1;
public static final String DATABASE_NAME = "FeedReader.db";
public static final String TABLE_TIME_ENTRIES = "time_entries";
//public static final String _ID = "_id"; // now in basecolumns
public static final String COLUMN_CENTER_OF_DAY = "center_of_day";
public static final String COLUMN_TIME = "time";
public static final String COLUMN_TIME_ENTRY_TYPE = "time_entry_type";
public static final String COLUMN_WAKEUP_OR_BEDTIME = "wakeup_or_bedtime";
public TimeEntryDbHandler(Context context) {
super (context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
String CREATE_TIME_ENTRIES_TABLE = "CREATE TABLE " + TABLE_TIME_ENTRIES + "("
+ _ID + " INTEGER PRIMARY KEY,"
+ COLUMN_CENTER_OF_DAY + " INTEGER,"
+ COLUMN_TIME + " INTEGER,"
+ COLUMN_TIME_ENTRY_TYPE + " TEXT,"
+ COLUMN_WAKEUP_OR_BEDTIME + " TEXT"
+ ")";
db.execSQL(CREATE_TIME_ENTRIES_TABLE);
}
// Method to add new time entry row to time entries table
public long addTimeEntry(TimeEntry timeEntry) {
ContentValues values = new ContentValues();
values.put(COLUMN_CENTER_OF_DAY, timeEntry.get_centerOfDay());
values.put(COLUMN_TIME, timeEntry.get_time());
values.put(COLUMN_TIME_ENTRY_TYPE, timeEntry.get_timeEntryType().name());
values.put(COLUMN_WAKEUP_OR_BEDTIME, timeEntry.get_direction().name());
SQLiteDatabase db = this.getWritableDatabase();
long newRowId;
newRowId = db.insert(TABLE_TIME_ENTRIES, null, values);
db.close();
return newRowId;
}
有誰知道爲什麼數據庫不是僅僅讓寫進_id列遞增的整數?否則,你有什麼建議我來調試呢?
我也嘗試了onCreate SQL命令中的'AUTO INCREMENT'指令,但是這並沒有改變任何東西。
如果需要發佈項目代碼的其他區域,請告訴我它是什麼,然後發佈它。
非常感謝!
雖然這個問題顯示了對這個問題正在做的很好的研究,但是它缺少關於它所屬的SE站點的研究:)我已經標記爲遷移到[SO]。 – Izzy
INTEGER PRIMARY KEY列*不能*爲空白。你有沒有改變'onCreate'函數? –
嗯我不確定,但有可能我在某些時候改變了onCreate函數。這怎麼會影響事情? – Meiji