Home » Android » sqlite – Android: Increment DB field via ContentValues

sqlite – Android: Increment DB field via ContentValues

Posted by: admin May 14, 2020 Leave a comment

Questions:

I’m updating an item in a ListView via the getContentResolver().update() method, and I’d like to increment a ‘views’ field via a ContentValue, but can’t figure out if this is possible.

I could do this with raw SQL SET views = views + 1, but setting a ContentValue, such as cv.put("views", "views + 1") results in the views field being set explicitly to “views + 1” rather than a number.

Any pointers on this on, or am I left to a more manual approach?

Thanks,

Paul

UPDATE:

I’ve gone back to using raw SQL to perform the update for now, and then manually notify the underlying CursorAdapter of the change via getContentResolver().notifyChange(). Would still be great if I could figure out a way to do this directly via getContentResolver().update(), so if anyone has a way to do that, please post it here.

How to&Answers:

My final solution to this was to use a custom Uri (along the lines of ...item/5/updateviews) via the ContentProvider such that a call to getContentResolver().update(customUri, ...) passing this Uri tells my ContentProvider’s overridden update() method to increment the view count for this item, thus avoiding the need to pass values to update() via it’s ContentValues parameter.

Answer:

I implemented the call API on my content provider as a way of sending raw/one-off SQL queries directly to the underlying SQLiteDatabase. It was easy enough.

Answer:

String key = "1";//some value where you want to update
int currentCount = 5;//the existing value of the count field

ContentValues values = new ContentValues();
values.put("my_counter_field", currentCount + 1);
int updatedRows = database.update("my_table_name", values, "my_where_field = ?", new String[] {key});

something like that for using ContentValues.

a possibly simpler route may be:
database.execSQL("UPDATE my_table_name SET my_counter_field = my_counter_field + 1 WHERE my_where_field = ?", new Object[] {key});

or maybe even use a Trigger. See this question to see if it suites your needs: Use trigger for auto-increment