How to use bulkInsert() function in android?
Asked Answered
H

3

8

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

Hexa answered 4/10, 2012 at 15:42 Comment(0)
A
38

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 == -1) { // error
                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.

Ample answered 4/10, 2012 at 17:10 Comment(5)
This will not finish the remaining inserts if one fails right?Atonement
This will revert / rollback every single one insert if there is any exception before calling setTransactionSuccessful in that try / catch block. In short if there is a exception you will get no insert at all.Ample
I got an error saying Variable 'table' might not have been initialized. Setting the declaration to String table = ""; solved the problem.Scarfskin
It great a help. but I'm afraid of isn't it crashed the app?Bobstay
if (newID <=0) is not correct. Zero is a valid value. It should be if (newId<0 or if (newID == -1). See developer.android.com/reference/android/database/sqlite/…Zerlina
R
6

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.

Rajasthan answered 18/8, 2014 at 20:1 Comment(0)
K
0

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

Kamseen answered 26/11, 2017 at 15:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.