0

I am struggling with using the update function of Sqlite in my android app. I am simply trying to add 1 to the value that already exists in a row.

This is what I currently have:

 public void updateItemQty(int SKU) {
        SQLiteDatabase db = getWritableDatabase();
        String p[] = new String[]{String.valueOf(SKU)};
        ContentValues args = new ContentValues();
        args.put(Keys.Key_SENTQTY, Keys.Key_SENTQTY + 1);
        try {
            db.update(Keys.Key_CARTONITEMTABLE, args, Keys.Key_SKU + " = ? AND " + Keys.Key_STATUS + " = 0 ", p);
        } catch (SQLiteException e) {
            e.printStackTrace();
        }

        db.close();
    }

This issue being that instead of adding 1 to my key.KEY_SENTQTY, it just enters sent_qty1 into the table! How do I achieve what I am after?

Thanks

3
  • 1
    db.rawQuery with standard UPDATE code for such cases(update table set col1 = col1 + 1 where col2=somevalue) or read value first add 1 in java code and then update with new value using db.update (for safe you should use transaction) ... there is no way to increment/add value directly using db.update Commented Jul 24, 2014 at 12:22
  • @selvin, whack this an answer and I will mark it correct Commented Jul 24, 2014 at 12:29
  • nah, i'm too lazy, you can always answer itself :) Commented Jul 24, 2014 at 12:30

3 Answers 3

1

technically, you could set sent_qty to sent_qty + 1, but not using contentValues, as these are escaped thoroughly.

Using execSQL, you can do:

db.execSQL("update " + Keys.Key_CARTONITEMTABLE 
         + " set " + Keys.Key_SENTQTY + " = " + Keys.Key_SENTQTY + " + 1 where " 
         + Keys.Key_SKU + " = " + SKU + " and " + Keys.Key_STATUS + " = 0");
Sign up to request clarification or add additional context in comments.

Comments

0

It's because Keys.KEY_SENTQTY is a String. How are you supposed to add an int to a String?

1 Comment

Badly explained but kind of right, the reason being that ContentValues are set pre-query, so there is no value to Keys.KEY_SENTQTY
0

After a bit of research and be pointed in the right direction by @Selvin, this is not possible as ContentValues are set pre-query, so you don't have the value of a row to add too.

My Assumption was that this was executed when the query was run, which was incorrect.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.