在之前提供了小例子BookProvider,我们回过头看看如何将通过该Content Provider进行数据的读取。
(1)增加
private void addBook(String name ,String isbn,String author){
/* 从ContentProvider的insert()方法的参数可以看到,通过ContentValues来进行数据的传递。ContentValues是key/values对,可以存储多个组,非常适合传递信息 */
ContentValues cv = new ContentValues(); cv.put(BookTableMetaData.BOOK_NAME, name);
cv.put(BookTableMetaData.BOOK_ISBN, isbn);
cv.put(BookTableMetaData.BOOK_AUTHOR, author);
/* ContentResolver负责将URI reference解析到正确的provider上,并对该provider的公开的读写接口进行操作。它的方法和provider提供的方法一一对应,并增加了uri参数。*/
ContentResolver cr = getContentResolver(); Uri insertUri = cr.insert(BookProviderMetaData.BookTableMetaData.CONTENT_URI, cv); //对应BookProvider的insert()
}
(2)删除
private void delBook(String name){
ContentResolver cr = getContentResolver();
int count = cr.delete(BookProviderMetaData.BookTableMetaData.CONTENT_URI, /* Uri uri */
BookTableMetaData.BOOK_NAME + "=?", /* String WhereClause */
new String[]{name}); /* String[] selectionArgs */
}
(3)修改: update和insert非常相似,也是通过ContentValues传递修改内容。
private void updateBookIsbn(String name ,String newIsbn,String newAuthor){
ContentValues cv = new ContentValues();
cv.put(BookTableMetaData.BOOK_NAME, name);
cv.put(BookTableMetaData.BOOK_ISBN, newIsbn);
cv.put(BookTableMetaData.BOOK_AUTHOR, newAuthor);
ContentResolver cr = getContentResolver();
int count = cr.update(BookProviderMetaData.BookTableMetaData.CONTENT_URI, /* Uri uri */
cv, /* ContentValues values */
BookTableMetaData.BOOK_NAME + "=?", /* String WhereClause */
new String[]{name}); /* String[] selectionArgs */
}
(4)查询
private void showBooks(){
Uri uri = BookProviderMetaData.BookTableMetaData.CONTENT_URI;
/*方式一,通过managedQuery( )*/ @SuppressWarnings("deprecation")
Cursor c = managedQuery(uri, null, null, null, null); /* 方式二:利用ContentResolver的query来获取*/
// ContentResolver cr = getContentResolver();
// Cursor c = cr.query(uri, null, null, null, null); int iIndex = c.getColumnIndex(BookTableMetaData._ID);
int iName = c.getColumnIndex(BookTableMetaData.BOOK_NAME);
int iIsbn = c.getColumnIndex(BookTableMetaData.BOOK_ISBN);
int iAuthor = c.getColumnIndex(BookTableMetaData.BOOK_AUTHOR);
/* 需要注意,通过下面showInfo显示,各列的Id并非按我们的创建table的列的顺序,所以一定要先获取列的ID。至于row的_id,是按顺序提供,为当前最大的_id+1。但除非我们能很明确清楚,一般不使用这些系统内部安排的Id */ showInfo("ColumnIndex _id=" + iIndex + ",name=" + iName + ",isdn=" + iIsbn + ", author=" + iAuthor);
showInfo("Totle books : " + c.getCount());
for(c.moveToFirst(); !c.isAfterLast();c.moveToNext()){
String id = c.getString(iIndex);
String name = c.getString(iName);
String isbn = c.getString(iIsbn);
String author = c.getString(iAuthor);
showInfo("[" +id + "]" + "\t" + name + "\t" + isbn + "\t" + author);
}
c.close();
}