每一個應用程序都有一個ContentResolver實例,經過getContentResolver()方法能夠獲取:異步
ContentResolver cr = getContentResolver();
與Content Provider對應,Content Resolver用於使用Content Provider發佈的數據。使用ContentResolver查詢ConentProvider提供的數據:ide
// Get the Content Resolver. ContentResolver cr = getContentResolver(); // Specify the result column projection. Return the minimum set of columns required to satisfy your requirements. String[] result_columns = new String[] { MyHoardContentProvider.KEY_ID, MyHoardContentProvider.KEY_GOLD_HOARD_ACCESSIBLE_COLUMN, MyHoardContentProvider.KEY_GOLD_HOARDED_COLUMN }; // Specify the where clause that will limit your results. String where = MyHoardContentProvider.KEY_GOLD_HOARD_ACCESSIBLE_COLUMN + 「=」 + 1; // Replace these with valid SQL statements as necessary. String whereArgs[] = null; String order = null; // Return the specified rows. Cursor resultCursor = cr.query(MyHoardContentProvider.CONTENT_URI, result_columns, where, whereArgs, order);
從Cursor中解析數據的方法和上一篇博文中介紹的同樣,首先要移動到指定行,而後從指定列中獲取對應類型的數據:ui
float largestHoard = 0f; String hoardName = 「No Hoards」; // Find the index to the column(s) being used. int GOLD_HOARDED_COLUMN_INDEX = resultCursor.getColumnIndexOrThrow( MyHoardContentProvider.KEY_GOLD_HOARDED_COLUMN); int HOARD_NAME_COLUMN_INDEX = resultCursor.getColumnIndexOrThrow( MyHoardContentProvider.KEY_GOLD_HOARD_NAME_COLUMN); // Iterate over the cursors rows. // The Cursor is initialized at before first, so we can // check only if there is a 「next」 row available. If the // result Cursor is empty, this will return false. while (resultCursor.moveToNext()) { float hoard = resultCursor.getFloat(GOLD_HOARDED_COLUMN_INDEX); if (hoard > largestHoard) { largestHoard = hoard; hoardName = resultCursor.getString(HOARD_NAME_COLUMN_INDEX); } } // Close the Cursor when you’ve finished with it. resultCursor.close();
Cursor Loader存在於在每一個Activity和Fragment中,能夠實現異步查詢和監聽底層數據的變化。例如管理Cursor的生命週期,確保在Activity退出以前Cursor被關閉。this
若要使用Cursor Loader,首先要實現LoaderManager.LoaderCallbacks接口:spa
LoaderManager.LoaderCallbacks<Cursor> loaderCallback = new LoaderManager.LoaderCallbacks<Cursor>()
LoaderCallback主要有這幾個回調方法:code
public Loader<Cursor> onCreateLoader(int id, Bundle args) { // Construct the new query in the form of a Cursor Loader. Use the id // parameter to construct and return different loaders. String[] projection = null; String where = null; String[] whereArgs = null; String sortOrder = null; // Query URI Uri queryUri = MyContentProvider.CONTENT_URI; // Create the new Cursor loader. return new CursorLoader(DatabaseSkeletonActivity.this, queryUri,projection, where, whereArgs, sortOrder); } public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) { // Replace the result Cursor displayed by the Cursor Adapter with the new result set. adapter.swapCursor(cursor); // This handler is not synchronized with the UI thread, so you will need to synchronize it before modifying any UI elements directly. } public void onLoaderReset(Loader<Cursor> loader) { // Remove the existing result Cursor from the List Adapter. adapter.swapCursor(null); // This handler is not synchronized with the UI thread, so you // will need to synchronize it before modifying any UI elements directly. }
在Activity和Fragment中,能夠調用getLoaderManager得到Cursor Loaderorm
LoaderManager loaderManager = getLoaderManager();
獲取Cursor Loader:blog
Bundle args = null; loaderManager.initLoader(LOADER_ID, args, myLoaderCallbacks);
LOADER_ID用於標識得到的loader,args是可選參數,myLoaderCallbacks則是前面LoaderManager.LoaderCallbacks接口的實現。若是對應LOADER_ID的Cursor Loader不存在,那麼系統會調用onCreateLoader方法來建立一個Loader。接口
插入數據:生命週期
// Create a new row of values to insert. ContentValues newValues = new ContentValues(); // Assign values for each row. newValues.put(MyHoardContentProvider.KEY_GOLD_HOARD_NAME_COLUMN, hoardName); newValues.put(MyHoardContentProvider.KEY_GOLD_HOARDED_COLUMN, hoardValue); newValues.put(MyHoardContentProvider.KEY_GOLD_HOARD_ACCESSIBLE_COLUMN, hoardAccessible); // [ ... Repeat for each column / value pair ... ] // Get the Content Resolver ContentResolver cr = getContentResolver(); // Insert the row into your table Uri myRowUri = cr.insert(MyHoardContentProvider.CONTENT_URI, newValues);
刪除數據:
// Specify a where clause that determines which row(s) to delete. // Specify where arguments as necessary. String where = MyHoardContentProvider.KEY_GOLD_HOARDED_COLUMN + 「=」 + 0; String whereArgs[] = null; // Get the Content Resolver. ContentResolver cr = getContentResolver(); // Delete the matching rows int deletedRowCount = cr.delete(MyHoardContentProvider.CONTENT_URI, where, whereArgs);
修改數據:
// Create the updated row content, assigning values for each row. ContentValues updatedValues = new ContentValues(); updatedValues.put(MyHoardContentProvider.KEY_GOLD_HOARDED_COLUMN, newHoardValue); // [ ... Repeat for each column to update ... ] // Create a URI addressing a specific row. Uri rowURI = ContentUris.withAppendedId(MyHoardContentProvider.CONTENT_URI, hoardId); // Specify a specific row so no selection clause is required. String where = null; String whereArgs[] = null; // Get the Content Resolver. ContentResolver cr = getContentResolver(); // Update the specified row. int updatedRowCount = cr.update(rowURI, updatedValues, where, whereArgs);
public void addNewHoardWithImage(String hoardName, float hoardValue, boolean hoardAccessible, Bitmap bitmap) { // Create a new row of values to insert. ContentValues newValues = new ContentValues(); // Assign values for each row. newValues.put(MyHoardContentProvider.KEY_GOLD_HOARD_NAME_COLUMN, hoardName); newValues.put(MyHoardContentProvider.KEY_GOLD_HOARDED_COLUMN, hoardValue); newValues.put(MyHoardContentProvider.KEY_GOLD_HOARD_ACCESSIBLE_COLUMN, hoardAccessible); // Get the Content Resolver ContentResolver cr = getContentResolver(); // Insert the row into your table Uri myRowUri = cr.insert(MyHoardContentProvider.CONTENT_URI, newValues); try { // Open an output stream using the new row’s URI. OutputStream outStream = cr.openOutputStream(myRowUri); // Compress your bitmap and save it into your provider. bitmap.compress(Bitmap.CompressFormat.JPEG, 80, outStream); }catch (FileNotFoundException e) { Log.d(TAG, 「No file found for this record.」); } } public Bitmap getHoardImage(long rowId) { Uri myRowUri = ContentUris.withAppendedId(MyHoardContentProvider.CONTENT_URI, rowId); try { // Open an input stream using the new row’s URI. InputStream inStream = getContentResolver().openInputStream(myRowUri); // Make a copy of the Bitmap. Bitmap bitmap = BitmapFactory.decodeStream(inStream); return bitmap; }catch (FileNotFoundException e) { Log.d(TAG, 「No file found for this record.」); } return null; }