开发者

Constraint Failed - SQLite 3 - Android

I has the following table on my SQLite.

    StringBuilder createSql = new StringBuilder();
    createSql.append("create table LIBRARY ( ");
    createSql.append("id integer primary key, ");
    createSql.append("title text, ");
    createSql.append("author text, ");
    createSql.append("publisher text, ");
    createSql.append("thumbnailUrl text, ");
    createSql.append("formatType text, ");
    createSql.append("contentUrl text, ");
    createSql.append("publicationType text, ");
    createSql.append("favorite text, ");
    createSql.append("started text, ");
    createSql.append("normalizedTitle text, ");
    createSql.append("downloaded integer, ");
    createSql.append("wasDownloaded text ");
    createSql.append(");");

And the following code to inser a value on that Table.

public void addLibrary(LibraryItem item) {
    ContentValues row = new ContentValues();
    row.put("title", item.getTitle());
    row.put("author", item.getAuthor());
    row.put("publisher", item.getPublisher());
    row.put("thumbnailUrl", item.getThumbnail());
    row.put("formatType", item.getFormat());
    row.put("contentUrl", item.getContentUrl());
    row.put("publicationType", item.getPublicationType());
    row.put("favorite", item.isFavorite() ? "YES" : "NO");
    row.put("id", item.getItemId());
    row.put("normalizedTitle", StringUtil.normalize(item.getTitle()));
    row.put(开发者_如何学Go"downloaded", Calendar.getInstance().getTimeInMillis());
    row.put("wasdownloaded", item.hasContent() ? "YES" : "NO");

    long id = db.insert("LIBRARY", null, row);
    add(id, item.getCategories());
}

But when executing it, I got the following error.

Error inserting id=255 formatType=null author=null title=A Cabana contentUrl=/sdcard/Digital Editions/A Cabana.pdf publicationType=Livro thumbnailUrl=https://api-dls.homolog.abrildigital.com.br/images/22/android_cover_201103092041.jpg wasdownloaded=NO downloaded=1302631109426 normalizedTitle=A Cabana favorite=NO publisher=null
android.database.sqlite.SQLiteConstraintException: error code 19: constraint failed

What's wrong?


Your primary key isn't auto incrementing. Then you are inserting first row it is got a key, and then you are inserting another one it is got the same one but the primary key can't be same!

Then you are inserting an item with specified key i think the error means what item with this key is already exists.


Change your createSQL builder to...

createSql.append("id integer primary key autoincrement, ");

Also. When you're doing your insert, you don't set the id field. Instead, what you should do, is do a check at the top of the function.

if(item.getItemID() == 0)
{
    //Run update here instead.
    //Set the id on the ContentValues here
}
else
{
    //Run insert statement instead.
    //Don't set the id in the ContentValues here.
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜