SQLite UPDATE statement updates all row in table

129 views Asked by At

When adding a new row to my table, I check if the row already exist, if it does, I update the row else a new row is created. This works fine when I have only one row in my table. But when I add another row and perform the same operation, all the rows in the table are updated.

Am working with these test data:

Test 1

debtorName: Ann Droid
totalOwed = 200

and this is the result:

enter image description here

When I run the app again with the same test data, I get this result (as expected) enter image description here

Test 2

debtorName: Vera Brown
totalOwed: 700

I get the expected result, nothing changes in the first row: enter image description here

but when I try to update add a new record for the second row with this test data (or any other)

debtorName: Vera Brown
amountOwed: 200

this happens:

enter image description here

I've been trying to figure this out for the past 24 hours with no luck. This is the update code:

public boolean updateRecord(String id,  int newTotalDebt, double newTotalOwed) {

    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues contentValues = new ContentValues();

    int newTotalDebts = newTotalDebt + getDebtor(id).getTotalDebts();
    double newTotalMoneyOwed = newTotalOwed + getDebtor(id).getTotalAmountOwed();


    contentValues.put(TOTAL_DEBTS, newTotalDebts);
    contentValues.put(TOTAL_OWED, newTotalMoneyOwed);

    return db.update(DEBTOR_TABLE_NAME, contentValues, id, null) > 0;
    //db.close();


}

Any help is welcome.

2

There are 2 answers

0
Ojonugwa Jude Ochalifu On

Finally solved it by changing my update code to this:

public boolean updateRecord(String id,  int newTotalDebt, double newTotalOwed) {

    String filter = DEBTOR_ID +"= '" +id +"'";
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues contentValues = new ContentValues();

    int newTotalDebts = newTotalDebt + getDebtor(id).getTotalDebts();
    double newTotalMoneyOwed = newTotalOwed + getDebtor(id).getTotalAmountOwed();


    contentValues.put(TOTAL_DEBTS, newTotalDebts);
    contentValues.put(TOTAL_OWED, newTotalMoneyOwed);

    return db.update(DEBTOR_TABLE_NAME, contentValues, filter, null) > 0;
    //db.close();


}
0
kevin On

in your DebtDatabaseHandler class function "public boolean updateRecord(String id, int newTotalDebt, double newTotalOwed)" shows that this function need three arguments one is id which will be primary key so you have to provide id of row which you want to update.