I have a table in my database, when adding new record I am checking if the record exists using the id.If it does, I want to update the record and if it doesn't add a new record. But am getting the exception:
2006-2259/? E/SQLiteDatabase﹕ Error inserting id=080333 phone=080333 total_owed=15050.0 total_debts=0 name=Alison Jones android.database.sqlite.SQLiteConstraintException: column id is not unique (code 19)
This is the method that checks if a record exists:
public boolean checkIfExists(String tableName, String value) {
SQLiteDatabase database = this.getReadableDatabase();
String Query = "Select * from " + tableName + " where " + DEBTOR_ID + " = " + value;
Cursor cursor = database.rawQuery(Query, null);
if(cursor.getCount() <= 0){
cursor.close();
return false;
}
cursor.close();
return true;
}
and it is being used here:
debtor.setDebtorName(params[0]);
debtor.setPhoneNumber(params[1]);
debtor.setTotalAmountOwed(Double.parseDouble(params[6]));
debtor.setTotalDebts(0);
if (databaseHandler.checkIfExists(DebtDatabaseHandler.DEBTOR_TABLE_NAME, params[1])) {
Log.d("NewDebtFragment", "Record already exist");
databaseHandler.updateRecord(2, debtor.getTotalAmountOwed() + 50000);
} else {
debtorId = databaseHandler.addDebtor(debtor);
}
Since this is a conflict issue, obviously the check for existing record isn't working.I don't why this is because the code seem fine (?)
This is how am creating the table:
String CREATE_DEBTOR_TABLE = "CREATE TABLE " + DEBTOR_TABLE_NAME + " ( " +
DEBTOR_ID + " TEXT PRIMARY KEY, " +
DEBTOR_NAME + " TEXT, " +
PHONE_NUMBER + " TEXT, "+
TOTAL_DEBTS + " INTEGER, " +
TOTAL_OWED + " INTEGER) ";
and the updateRecord
method:
public void updateRecord(int newTotalDebt, double newTotalOwed) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(TOTAL_DEBTS, newTotalDebt);
contentValues.put(TOTAL_OWED, newTotalOwed);
db.update(DEBTOR_TABLE_NAME, contentValues, DEBTOR_ID, null);
}