MediaInserter.java revision 8e2ed8d512ade2ea481b3a292556782b17a74674
1/* 2 * Copyright (C) 2011 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package android.media; 18 19import android.content.ContentValues; 20import android.content.IContentProvider; 21import android.net.Uri; 22import android.os.RemoteException; 23 24import java.util.ArrayList; 25import java.util.HashMap; 26import java.util.List; 27 28/** 29 * A MediaScanner helper class which enables us to do lazy insertion on the 30 * given provider. This class manages buffers internally and flushes when they 31 * are full. Note that you should call flushAll() after using this class. 32 * {@hide} 33 */ 34public class MediaInserter { 35 private HashMap<Uri, List<ContentValues>> mRowMap = 36 new HashMap<Uri, List<ContentValues>>(); 37 38 private IContentProvider mProvider; 39 private int mBufferSizePerUri; 40 41 public MediaInserter(IContentProvider provider, int bufferSizePerUri) { 42 mProvider = provider; 43 mBufferSizePerUri = bufferSizePerUri; 44 } 45 46 public void insert(Uri tableUri, ContentValues values) throws RemoteException { 47 List<ContentValues> list = mRowMap.get(tableUri); 48 if (list == null) { 49 list = new ArrayList<ContentValues>(); 50 mRowMap.put(tableUri, list); 51 } 52 list.add(new ContentValues(values)); 53 if (list.size() >= mBufferSizePerUri) { 54 flush(tableUri); 55 } 56 } 57 58 public void flushAll() throws RemoteException { 59 for (Uri tableUri : mRowMap.keySet()){ 60 flush(tableUri); 61 } 62 mRowMap.clear(); 63 } 64 65 private void flush(Uri tableUri) throws RemoteException { 66 List<ContentValues> list = mRowMap.get(tableUri); 67 if (!list.isEmpty()) { 68 ContentValues[] valuesArray = new ContentValues[list.size()]; 69 valuesArray = list.toArray(valuesArray); 70 mProvider.bulkInsert(tableUri, valuesArray); 71 list.clear(); 72 } 73 } 74} 75