android SqliteDatabase错误:插入列值

时间:2013-08-19 06:22:41

标签: android

我正在创建一个应用程序,我需要将一些值保存到sqlitedatabase,为此我写了这个函数

public long saveMood(Mood mood) {
        openDatabase();
        ContentValues cv = new ContentValues();
        cv.put(COL_ACTIVE, (mood.isActive() ? 1 : 0));
        cv.put(COL_BLOCK_CALL, (mood.isBlockCall() ? 1 : 0));
        cv.put(COL_BLOCK_CALL, (mood.isBlockCall() ? 1 : 0));
        cv.put(COL_BLOCK_SMS, (mood.isBlockSms() ? 1 : 0));
        cv.put(COL_SILENT, (mood.isSilent() ? 1 : 0));
        cv.put(COL_VIBRATE, (mood.isVibrate() ? 1 : 0));
        cv.put(COL_WIFI, (mood.isWifiOn() ? 1 : 0));
        cv.put(COL_TIME, mood.getTime());
        cv.put(COL_NAME, mood.getName());
        cv.put(COL_VOLUME, mood.getRingVolumn());
        long id = database.insert(TABLE_NAME, null, cv);
        closeDatabase();
        return id;
    }

我用来创建表的查询是

private static final String CREATE_TABLE_QUERY = "CREATE TABLE " + TABLE_NAME 
                    + "("
                    + COL_ID + " INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " 
                    + COL_NAME + " TEXT NOT NULL, " 
                    + COL_ACTIVE + " INTEGER NOT NULL, "
                    + COL_BLOCK_CALL + " INTEGER NOT NULL, "
                    + COL_BLOCK_SMS + " INTEGER NOT NULL, "
                    + COL_BRIGHT + " INTEGER NOT NULL, "
                    + COL_SILENT + " INTEGER NOT NULL, "
                    + COL_TIME + " LONG NOT NULL, "
                    + COL_VIBRATE + " INTEGER NOT NULL, "
                    + COL_VOLUME + " INTEGER NOT NULL, "
                    + COL_WIFI + " INTEGER NOT NULL "
                    + " ); ";

但是我每次都使用insert id = -1

获得此异常
 Error inserting silent=1 call_block=1 time=0 wifi=0 name=night volume=0 sms_block=1 vibrate=0 active=0
08-19 11:09:05.790: E/Database(6648):   at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1658)
08-19 11:09:05.790: E/Database(6648):   at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1519)

请帮帮我!

3 个答案:

答案 0 :(得分:1)

所有列都有not null约束。但错误日志显示:

silent=1 call_block=1 time=0 wifi=0 name=night volume=0 sms_block=1 vibrate=0 active=0

这意味着缺少volumebright的值,SQLite将不接受此插入,因为表要求所有记录值都不为空。

答案 1 :(得分:0)

这里几乎没有什么问题

首先

COL_BRIGHT + " INTEGER NOT NULL,"

不是NULL,但是您没有在saveMood方法中为此提供值。所以这就是Conflict

的原因

解决方案

COL_BRIGHT提供值或移除NOT NULL

<强>第二

这似乎重复了一行

cv.put(COL_BLOCK_CALL, (mood.isBlockCall() ? 1 : 0));
cv.put(COL_BLOCK_CALL, (mood.isBlockCall() ? 1 : 0));

解决方案

删除重复的行

答案 2 :(得分:0)

您需要在Create Query的主键中删除NOT NULL关键字,因为具有autoincreament的主键在任何情况下都不会为null 或者使用insertWithOnConflict()方法而不是insert()方法