Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update item in database without all of the columns set in ContentValues

For example, I have four columns: first_name, last_name, phone_number and picture. Somewhere in my code there's:

ContentValues values = new ContentValues();
values.put(MyPerson.FIRST_NAME, "Ted");
values.put(MyPerson.LAST_NAME, "Johnson");
values.put(MyPerson.PHONE_NUMBER, "111-111-1111");
values.put(MyPerson.PICTURE, "file://tedpicture.jpeg");

getContentResolver().update(tedUri, values, null, null);

Could I run something like:

ContentValues values = new ContentValues();
values.put(MyPerson.PHONE_NUMBER, "222-222-2222");

getContentResolver().update(tedUri, values, null, null);

And expect the first_name,last_name, and picture columns to have the same values as when I first set them. Or do I have to also populate the first_name, last_name, and picture columns too?

like image 838
Mohit Deshpande Avatar asked Dec 21 '22 19:12

Mohit Deshpande


1 Answers

To answer your question, yes you can pass just one field of data to the update and it will update that column without affecting any others.

The problem you currently have, by the looks of it, you are not telling the DB which record you want to update.

As per the update method:

public int update (String table, ContentValues values, String whereClause, String[] whereArgs)

You are passing null for the where part of the method.

If you pass a where part to the method it will update just the specific entry(s).

ContentValues values = new ContentValues();
values.put(MyPerson.PHONE_NUMBER, "222-222-2222");
getContentResolver().update(tedUri, values, "first_name = ?", new String[] { "tom" });

Would update anyone with the first name tom to have the phone number 222-222-2222

like image 127
Scoobler Avatar answered Dec 29 '22 01:12

Scoobler