【发布时间】:2012-09-25 16:53:59
【问题描述】:
在所有批量插入数据库完成后,我只需要一个通知。 请提供一个使用 bulkInsert() 函数的示例。 我在互联网上找不到合适的例子。请帮忙!!!!
【问题讨论】:
标签: android android-contentprovider bulkinsert
在所有批量插入数据库完成后,我只需要一个通知。 请提供一个使用 bulkInsert() 函数的示例。 我在互联网上找不到合适的例子。请帮忙!!!!
【问题讨论】:
标签: android android-contentprovider bulkinsert
这是使用 ContentProvider 的 bulkInsert。
public int bulkInsert(Uri uri, ContentValues[] values){
int numInserted = 0;
String table;
int uriType = sURIMatcher.match(uri);
switch (uriType) {
case PEOPLE:
table = TABLE_PEOPLE;
break;
}
SQLiteDatabase sqlDB = database.getWritableDatabase();
sqlDB.beginTransaction();
try {
for (ContentValues cv : values) {
long newID = sqlDB.insertOrThrow(table, null, cv);
if (newID <= 0) {
throw new SQLException("Failed to insert row into " + uri);
}
}
sqlDB.setTransactionSuccessful();
getContext().getContentResolver().notifyChange(uri, null);
numInserted = values.length;
} finally {
sqlDB.endTransaction();
}
return numInserted;
}
只有在 ContentValues[] values 数组中有更多 ContentValues 时才调用一次。
【讨论】:
Variable 'table' might not have been initialized。将声明设置为String table = ""; 解决了问题。
我一直在寻找一个教程来在活动方面和内容提供者方面实现这一点。我从上面使用了“术士”的答案,它在内容提供者方面效果很好。我使用来自this post 的答案在活动端准备 ContentValues 数组。我还修改了我的 ContentValues 以从一串逗号分隔值(或新行、句点、分号)中接收。看起来像这样:
ContentValues[] bulkToInsert;
List<ContentValues>mValueList = new ArrayList<ContentValues>();
String regexp = "[,;.\\n]+"; // delimiters without space or tab
//String regexp = "[\\s,;.\\n\\t]+"; // delimiters with space and tab
List<String> splitStrings = Arrays.asList(stringToSplit.split(regexp));
for (String temp : splitStrings) {
Log.d("current student name being put: ", temp);
ContentValues mNewValues = new ContentValues();
mNewValues.put(Contract.KEY_STUDENT_NAME, temp );
mNewValues.put(Contract.KEY_GROUP_ID, group_id);
mValueList.add(mNewValues);
}
bulkToInsert = new ContentValues[mValueList.size()];
mValueList.toArray(bulkToInsert);
getActivity().getContentResolver().bulkInsert(Contract.STUDENTS_CONTENT_URI, bulkToInsert);
我找不到一种更简洁的方法将划定的拆分字符串直接附加到 bulkInsert 的 ContentValues 数组。但是这个功能直到我找到它。
【讨论】:
试试这个方法。
public int bulkInsert(@NonNull Uri uri, @NonNull ContentValues[] values) {
final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
switch (sUriMatcher.match(uri)) {
case CODE_WEATHER:
db.beginTransaction();
int rowsInserted = 0;
try {
for (ContentValues value : values) {
long _id = db.insert(WeatherContract.WeatherEntry.TABLE_NAME, null, value);
if (_id != -1) {
rowsInserted++;
}
}
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
if (rowsInserted > 0) {
getContext().getContentResolver().notifyChange(uri, null);
}
return rowsInserted;
default:
return super.bulkInsert(uri, values);
}
}
术士的回答要么插入全部行,要么不插入行。另外,在setTransactionSuccessful() 和endTransaction() 之间做最少的任务,当然这两个函数调用之间没有数据库操作。
代码来源:Udacity
【讨论】: