Search code examples
javaandroidsqlsqliteopenhelper

How to update entry in SQLiteOpenHelper without entryId?


So for my android app, I want to update a row of data that I initially entered through the standard methods below that are within a class that extends SQLiteOpenHelper:

public boolean insert(String name, int quantity, double price){
    ContentValues contentValues = new ContentValues();
    contentValues.put(DatabaseContract.Table.COLUMN_NAME_NAME, name);
    contentValues.put(DatabaseContract.Table.COLUMN_NAME_QUANTITY, quantity);
    contentValues.put(DatabaseContract.Table.COLUMN_NAME_PRICE, price);
    long result = db.insert(DatabaseContract.Table.TABLE_NAME, null, contentValues);
    if (result == -1)
        return false;
    else
        return true;
}

public void updateData(int id, String name, int quantity, double price){
        ContentValues contentValues = new ContentValues();
        contentValues.put(DatabaseContract.Table.COLUMN_NAME_ID, id);
        contentValues.put(DatabaseContract.Table.COLUMN_NAME_NAME, name);
        contentValues.put(DatabaseContract.Table.COLUMN_NAME_QUANTITY, quantity);
        contentValues.put(DatabaseContract.Table.COLUMN_NAME_PRICE, price);
        db.update(DatabaseContract.Table.TABLE_NAME, contentValues, "ID = ?", new String[]{Integer.toString(id)});
    } 

Within my actual activity, I have the name, quantity, and price I want to change, but I am puzzled as to how to go about it when I don't know the "id" of the arbitrary entry.

Thanks in advance.


Solution

  • Rather than returning a boolean, I would return the ID of the new record. Let's say for instance your app has something to do with a Store and your name, quantity, and price are attributes of the Item class, I would add an ID attribute to your item as well. On your save (create) you set the ID in your item. This will allow you to update it using this same ID later on. If not, you would need some quantity of other attributes to serve as a primary key but this doesn't seem like what you are looking for, nor is it a great option.