更新数据库中的项目,而不在ContentValues中设置所有列

例如,我有四列: first_namelast_namephone_numberpicture 。 在我的代码中的某处:

 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); 

我可以运行类似的东西:

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

并期望first_namelast_namepicture列具有与我第一次设置时相同的值。 或者我是否还必须填充first_namelast_namepicture列?

要回答您的问题,是的,您只能将一个数据字段传递给更新,它将更新该列而不会影响任何其他列。

您目前遇到的问题是,从外观上看,您并没有告诉数据库要更新哪条记录。

根据更新方法:

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

您正在为方法的where部分传递null。

如果将where部分传递给方法,它将仅更新特定条目。

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

将更新名字为tom的任何人使用电话号码222-222-2222

这将完全按照您的描述工作,只会更新设定值。

您可以在update function 3rd参数中设置where子句

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