Multiple rows insert with ContentProvider

后端 未结 4 2001
醉话见心
醉话见心 2021-02-02 00:23

I need to make insert of few rows in one transaction. Can I do it with ContentProvider?

4条回答
  •  [愿得一人]
    2021-02-02 00:54

    Here an example for bulkInsert:

    /**
     * Perform bulkInsert with use of transaction
     */
    @Override
    public int bulkInsert(Uri uri, ContentValues[] values) {
        int uriType = 0;
        int insertCount = 0;
        try {
    
            uriType = sURIMatcher.match(uri);
            SQLiteDatabase sqlDB = dbHelper.getWritableDatabase();
    
            switch (uriType) {
            case MEASUREMENTS:
                try {
                    sqlDB.beginTransaction();
                    for (ContentValues value : values) {
                        long id = sqlDB.insert(Tab_Measurements.TABLE_NAME, null, value);
                        if (id > 0)
                            insertCount++;
                    }
                    sqlDB.setTransactionSuccessful();
                } catch (Exception e) {
                    // Your error handling
                } finally {
                    sqlDB.endTransaction();
                }
                break;
            default:
                throw new IllegalArgumentException("Unknown URI: " + uri);
            }
            // getContext().getContentResolver().notifyChange(uri, null);
        } catch (Exception e) {
          // Your error handling
        }
    
        return insertCount;
    }
    

    And in your code something like:

    /**
     * Inserts new measurement information.
     * 
     * @param ArrayList of measurements
     * @return number of inserted entries
     */
    public static long bulkInsertEntries(ArrayList readings) {
        // insert only if data is set correctly
        if (readings.size() == 0)
            return 0;
    
        long insertCount = 0;
        try {
            // insert new entries
    
            // ArrayList valueList = new ArrayList();
            ContentValues[] valueList = new ContentValues[readings.size()];
            int i = 0;
            for (Item_Measurement reading : readings) {
                ContentValues values = new ContentValues();
                values.put(COL_TIME_READING, reading.getTimeReading());
                                // ...
                valueList[i++] = values;
            }
    
            // returns ID
            insertCount = ContentProviderOwn.getAppContext().getContentResolver()
                    .bulkInsert(ContentProviderOwn.MEASUREMENTS_URI_BASE, valueList);
    
        } catch (Exception e) {
            // Your error handling
        }
        return insertCount;
    }
    

提交回复
热议问题