ContentProvider - 重写bulkInsert()方法

默认重写bulkInsert方法

    @Override
    public int bulkInsert(Uri uri, ContentValues[] values) {
        return super.bulkInsert(uri, values);
    }

bulkInsert()方法内部实现

/**
* Override this to handle requests to insert a set of new rows, or the
* default implementation will iterate over the values and call
* {@link #insert} on each of them.
* As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
* after inserting.
* This method can be called from multiple threads, as described in
* <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
* and Threads</a>.
*
* @param uri The content:// URI of the insertion request.
* @param values An array of sets of column_name/value pairs to add to the database.
*    This must not be {@code null}.
* @return The number of values that were inserted.
*/
public int bulkInsert(Uri uri, ContentValues[] values) {
    int numValues = values.length;
    for (int i = 0; i < numValues; i++) {
        insert(uri, values[i]);
    }
    return numValues;
}

重写bulkInsert() – 事务处理

/**
 * 批量插入,调用方法如下:
 *
 * ContentValues[] arrayValues = new ContentValues[10];
 * //实例化每一个ContentValues
 * int count = resolver.bultInsert(Student.CONTENT_URI,arrayValues);
 *
 * @param uri
 * @param values
 * @return
 */
@Override
public int bulkInsert(Uri uri, ContentValues[] values) {
    //return super.bulkInsert(uri, values);
    int numValues = 0;
    db.beginTransaction(); //开始事务
    try {
        //数据库操作
        numValues = values.length;
        for (int i = 0; i < numValues; i++) {
            insert(uri, values[i]);
        }
        db.setTransactionSuccessful(); //别忘了这句 Commit
    } finally {
        db.endTransaction(); //结束事务
    }
    return numValues;
}
    原文作者:康熙微博私访记
    原文地址: https://www.jianshu.com/p/21bf1f2f2070
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞