I want only a single notification after all the bulk insertion is done into database. Please provide an example to use bulkInsert() function. I cannot find a proper example on internet. Please Help!!!!
This is bulkInsert using ContentProvider.
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;
}
Call it only once when you will have more ContentValues in ContentValues[] values array.
I searched forever to find a tutorial to implement this on activity side and content provider side. I used "Warlock's" answer from above and it worked great on the content provider side. I used the answer from this post to prepare the ContentValues array on the activity end. I also modified my ContentValues to receive from a string of comma separated values (or new lines, periods, semi colons). Which looked like this:
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);
I couldn't find a cleaner way to attach the delineated split string straight to the ContentValues array for bulkInsert. But this functions until I find it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With