SQLiteConstraintException:UNIQUE约束失败

时间:2016-04-20 07:15:12

标签: android database sqlite

我查看了其他主题,但在代码中找不到我的错误。这是我创建数据库的代码

public class DBHelper extends SQLiteOpenHelper {

    //data base name
    private static final String DATABASE_NAME = "roomatesDB";

    //data base version
    private static final int DATABASE_VERSION = 1;

    //tables name
    public static final String APARTMENT_TABLE = "apartment";
    public static final String ROOMATE_TABLE = "roomate";
    public static final String SHOPCART_TABLE = "shopcart";
    public static final String ITEMS_TABLE = "items";

    //common column
    public static final String APARTMENT_NUMBER_COLUMN = "apartmentNum";

    //roomates table columns
    public static final String FIRST_NAME_COLUMN = "firstName";
    public static final String LAST_NAME_COLUMN = "lastName";
    public static final String PHONE_NUMBER_COLUMN = "phoneNumber";

    //shop cart table columns
    public static final String NUMBER_COLUMN = "number";
    public static final String LIST_NAME_COLUMN = "name";

    //item table
    public static final String PRICE_COLUMN = "price";
    public static final String ITEM_NAME_COLUMN = "name";

    //query for creating roomate table
    public static final String CREATE_ROOMATE_TABLE = "CREATE TABLE "
            + ROOMATE_TABLE + "(" + FIRST_NAME_COLUMN + " TEXT, "
            + LAST_NAME_COLUMN + " TEXT, " + PHONE_NUMBER_COLUMN + " TEXT, "
            + APARTMENT_NUMBER_COLUMN + " INTEGER, "
            + "FOREIGN KEY(" + APARTMENT_NUMBER_COLUMN + ") REFERENCES "
            + APARTMENT_TABLE + "(apartmentNum) " + ")";

    //query for crating shop cart table
    public static final String CREATE_SHOPLIST_TABLE = "CREATE TABLE "
            + SHOPCART_TABLE + "(" + NUMBER_COLUMN + " INTEGER PRIMARY KEY,"
            + LIST_NAME_COLUMN + " TEXT, "
            + APARTMENT_NUMBER_COLUMN + " INTEGER, "
            + "FOREIGN KEY(" + APARTMENT_NUMBER_COLUMN + ") REFERENCES "
            + APARTMENT_TABLE + "(apartmentNum) " + ")";

    //query for creating shop item table
    public static final String CREATE_SHOPITEM_TABLE = "CREATE TABLE "
            + ITEMS_TABLE + "(" + ITEM_NAME_COLUMN + " TEXT,"
            + PRICE_COLUMN + " DOUBLE, "
            + NUMBER_COLUMN + " INT, "
            + "FOREIGN KEY(" + NUMBER_COLUMN + ") REFERENCES "
            + SHOPCART_TABLE + "(number) " + ")";

    //query for creating apartment table
    public static final String CREATE_APARTMENT_TABLE = "CREATE TABLE "
            + APARTMENT_TABLE + "(" + APARTMENT_NUMBER_COLUMN + " INTEGER PRIMARY KEY"
            + ")";


    public DBHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);

    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(CREATE_APARTMENT_TABLE);
        db.execSQL(CREATE_ROOMATE_TABLE);
        db.execSQL(CREATE_SHOPLIST_TABLE);
        db.execSQL(CREATE_SHOPITEM_TABLE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS " + APARTMENT_TABLE);
        db.execSQL("DROP TABLE IF EXISTS " + ROOMATE_TABLE);
        db.execSQL("DROP TABLE IF EXISTS " + SHOPCART_TABLE);
        db.execSQL("DROP TABLE IF EXISTS " + ITEMS_TABLE);

        onCreate(db);

    }

并且用于检查即时尝试你在活动上执行这些功能

public void createApartment() {
    SQLiteDatabase db = this.getWritableDatabase();



    ContentValues values = new ContentValues();
    values.put(APARTMENT_NUMBER_COLUMN, 1);
    // Inserting Row
    db.insert(APARTMENT_TABLE, null, values);
    db.close(); // Closing database connection
}

public void addRoomate(RoomateModel r) {
        SQLiteDatabase db = this.getWritableDatabase();

        int i = 1;

        ContentValues values = new ContentValues();
        values.put(FIRST_NAME_COLUMN, r.getName()); // Contact Name
        values.put(LAST_NAME_COLUMN, r.getLastName());
        values.put(PHONE_NUMBER_COLUMN, r.getPhoneNumber()); // Contact Phone Number
        values.put(APARTMENT_NUMBER_COLUMN, i);
        // Inserting Row
        db.insert(ROOMATE_TABLE, null, values);
        db.close(); // Closing database connection
    }

    public RoomateModel getRoomates() {
        RoomateModel r = null;
        SQLiteDatabase db = this.getReadableDatabase();
        String query = "SELECT * FROM " + ROOMATE_TABLE + " WHERE 1";

        Cursor c = db.rawQuery(query, null);
        c.moveToFirst();
        while (!c.isAfterLast()) {
            String name = c.getString(0);
            String lastName = c.getString(1);
            String phoneNumber = c.getString(2);
            r = new RoomateModel(name, lastName, phoneNumber);
        }
        if (r == null) {
            r = new RoomateModel("bla", "bla", "bla");
        }

        return r;
    }

应用程序在加载活动之前崩溃 与主题中的错误 这是logcat:

Error Code : 1555 (SQLITE_CONSTRAINT_PRIMARYKEY)
Caused By : Abort due to constraint violation.
(UNIQUE constraint failed: apartment.apartmentNum (code 1555))
#################################################################
at android.database.sqlite.SQLiteConnection.nativeExecuteForLastInsertedRowId(Native Method)
at android.database.sqlite.SQLiteConnection.executeForLastInsertedRowId(SQLiteConnection.java:952)
at android.database.sqlite.SQLiteSession.executeForLastInsertedRowId(SQLiteSession.java:788)
at android.database.sqlite.SQLiteStatement.executeInsert(SQLiteStatement.java:86)
at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1609)
at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1479)
at atoa.roomates.SupportOperations.DBHelper.createApartment(DBHelper.java:106)
at atoa.roomates.QA.getRoomate(QA.java:49)
at atoa.roomates.QA.onCreate(QA.java:42)

2 个答案:

答案 0 :(得分:3)

您的桌面上有一个主键,因此它必须是唯一值。

public static final String CREATE_APARTMENT_TABLE = "CREATE TABLE "
        + APARTMENT_TABLE + "(" + APARTMENT_NUMBER_COLUMN + " INTEGER PRIMARY KEY"
        + ")";

然而,您总是在该列中插入值1。

values.put(APARTMENT_NUMBER_COLUMN, 1);
// Inserting Row
db.insert(APARTMENT_TABLE, null, values);

有几种方法可以解决这个问题,但您应该先使用不同的数字而不是始终使用1

答案 1 :(得分:1)

我认为就像cricket_007所说的那样,您正在尝试复制数据库中记录的ID,对此我不止使用了一次的快速解决方案是转到“设置”->“应用程序”->“您的应用程序”->“删除”存储,那么该应用将可以正常运行,尽管这不是一个好的解决方案,它只会通知您有关问题。解决此问题的真正方法是通过在每次添加新记录时添加例如表的大小来确保ID是唯一的,或者如果用户可以使用多个帐户为每个用户名创建目录,请尝试找出最适合您的情况。