Android ContentProvider批量插入数据

Android About 2,612 words

操作类中使用provider批量插入

public void insertCategoryInfo(List<CategoryInfo> categoryList) {
    ContentValues[] contentValues = new ContentValues[categoryList.size()];
    for (int i = 0; i < categoryList.size(); i++) {
        ContentValues value = new ContentValues();
        value.put("colName", categoryList.get(i).colName);
        value.put("colLogo", categoryList.get(i).colLogo);
        value.put("colSeq", categoryList.get(i).colSeq);
        value.put("colId", categoryList.get(i).colId);
        value.put("recName", categoryList.get(i).recName);
        value.put("operContent", categoryList.get(i).operContent);
        contentValues[i] = value;
    }
    mResolver.bulkInsert(UnicastUri.YP_TABLE_CATEGORY_URI, contentValues);
}

复写bulkInsert方法

@Override
public int bulkInsert(Uri uri, ContentValues[] values) {
    if (mDb == null) {
        Log.d("zbj1123", "bulkInsert: mDb为空!");
        return -1;
    }
    Log.d("zbj1123", "bulkInsert: 进入bulkInsert! values长度 : " + values.length);

    int numValues = 0;
    mDb.beginTransaction(); //开始事务
    try {
        //每次插入前都将之前的删除
        String table = getTableName(uri);
        if(table == null){
            throw new IllegalArgumentException("UnSupported URI : " + uri);
        }
        mDb.execSQL("delete from " + table + ";");
        //数据库操作
        numValues = values.length;
        for (int i = 0; i < numValues; i++) {
            insert(uri, values[i]);
        }
        mDb.setTransactionSuccessful(); //别忘了这句 Commit
    } finally {
        mDb.endTransaction(); //结束事务
    }
    return numValues;
}
public String getTableName(Uri uri){
    String tableName = null;
    switch (uriMatcher.match(uri)){
        case YP_TABLE_ENTERPRISE_URI_CODE :
            tableName = DBProviderColumns.YP_TABLE_ENTERPRISE;
            break;
        case YP_TABLE_CATEGORY_URI_CODE :
            tableName = DBProviderColumns.YP_TABLE_CATEGORY;
            break;
        case YP_TABLE_QUICK_URI_CODE :
            tableName = DBProviderColumns.YP_TABLE_QUICK;
            break;
        case YP_TABLE_CITY_LIST_URI_CODE :
            tableName = DBProviderColumns.YP_TABLE_CITY_LIST;
            break;
        case YP_TABLE_RECENT_CITY_URI_CODE :
            tableName = DBProviderColumns.YP_TABLE_RECENT_CITY;
            break;
        case YP_TABLE_RECENT_SEARCH_URI_CODE :
            tableName = DBProviderColumns.YP_TABLE_RECENT_SEARCH;
            break;
        case YP_TABLE_DATA_UPDATE_FREQUENCY_URI_CODE :
            tableName = DBProviderColumns.YP_TABLE_DATA_UPDATE_FREQUENCY;
            break;
    }
    return tableName;
}
Views: 4,542 · Posted: 2019-04-12

————        END        ————

Give me a Star, Thanks:)

https://github.com/fendoudebb/LiteNote

扫描下方二维码关注公众号和小程序↓↓↓

扫描下方二维码关注公众号和小程序↓↓↓


Today On History
Browsing Refresh