androidandroid-contentproviderbulkinsert

How to use bulkInsert() function in android?


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


Solution

  • 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.