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

青春壹個敷衍的年華 提交于 2019-12-04 13:22:25

问题


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?


回答1:


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




回答2:


That would work exactly as you described, only set values will be updated.




回答3:


You can set where clause in update function 3rd parameter

getContentResolver().update(tedUri, values, "first_name=?", new String
         [ ]{"name"});


来源:https://stackoverflow.com/questions/4706638/update-item-in-database-without-all-of-the-columns-set-in-contentvalues

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!