Home » Android » How to use bulkInsert() function in android?

How to use bulkInsert() function in android?

Posted by: admin June 15, 2020 Leave a comment

Questions:

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!!!!

How to&Answers:

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.

Answer:

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.

Answer:

Try this approach.

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

Warlock’s answer inserts either all or none rows. Also, do minimal tasks between setTransactionSuccessful() and endTransaction() and of course no database operations between these two function calls.

Code source : Udacity