Android, handle SQLiteConstraintException

*爱你&永不变心* 提交于 2019-12-05 00:55:27

Try using insertOrThrow. Otherwise, insert just returns -1 in the event of an error.

When you execute to add the values in the database from the entry class add boolean to control the data ex:

   boolean DBAccepted = DBhelper.addData(blabla);

if(DBAccepted ==false)
{
Toast.maketext (this,"There is a conflict",Toast.LengthLong ).show();
}

in the DBhelper Class :

public boolean addData(String blablabla){
    DBAccepted =true;
ContentValues cv = new ContentValues();
    cv.put(key_value, blablabla);
     Databes.insertOrThrow(TABLE_SCORES, null, cv);
    } catch (SQLiteConstraintException e) {
                // TODO Auto-generated catch block
                    System.out.println(e);
                    DBAccepted =false;
            }
        return DBAccepted ;
    }

The database here will try to add the values if the values passed without conflict or error the boolean will remain true if error the boolean will be false and will return it and you can toast any message as ex toast (there is a conflict)

Sorry but the answers mentioned above do not work for me on android 4.4.2. min sdk level 11, max 21.

What worked for me was the following:

/*FIRST INSERT A VALUE*/
database = //get a writable database instance
String MESSAGES_TABLE = "messages";
ContentValues cv= new ContentValues();
cv.put("unique_id_column","unique_id");
database.insert(MESSAGES_TABLE,null,cv);
database.close();



/*NOW LETS TRY TO INSERT ANOTHER RECORD, WITH THE SAME VALUE, WHERE UNIQUE_ID_COLUMN
IS THE UNIQUE COLUMN DEFINED WHILE CREATING THE TABLE.*/
database == //get a writable database instance
try{            
    long new_row_id = database.insertWithOnConflict(MESSAGES_TABLE, null,cv,SQLiteDatabase.CONFLICT_FAIL);
    Log.d(SS_DATABASE_TAG,"the new row id is ---> " + String.valueOf(new_row_id));          
    }
catch(SQLiteConstraintException e)
    {
    Log.d(SS_DATABASE_TAG,"caught the contraint.");
    }
database.close();

this correctly catches the constraint, and you can do your handling inside the catch block.

RR.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!