我有一个包含 3 行 _id、名称和编号的表。我必须用不同的值更新每一行的列号。实际上我的代码是:
ContentValues values;
ContentResolver cr = getContentResolver();
int n[] = new int[10];
// functions to assign the values to n[]
for(int i=1; i<31;i++) {
values = new ContentValues();
values.put("number", n[i]);
cr.update(MyProvider.CONTENT_URI_TABLE, values, "_id="+i, null);
}
在这种情况下,我必须使用大量更新和对数据库的多次访问。有没有办法简化程序?
最佳答案
为此,我会使用 applyBatch() ContentResolver 上的方法。基本上,它需要一个类型为 ContentProviderOperation 的数组。指定您要更新/插入/删除的内容。
虽然它不会简化您正在编写的代码,但它可能对您正在访问的内容提供者有益。这里的好处是内容提供者可以做一些事情,比如在事务中应用这些更新。
关于Android 用不同的值更新多行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13362429/