《Android基本-ContentProvider.ppt》由会员分享,可在线阅读,更多相关《Android基本-ContentProvider.ppt(14页珍藏版)》请在taowenge.com淘文阁网|工程机械CAD图纸|机械工程制图|CAD装配图下载|SolidWorks_CaTia_CAD_UG_PROE_设计图分享下载上搜索。
1、Android四大组件之ContentProvider,一、什么是ContentProvider,ContentProvider用来存储和检索数据 ContentProvider是应用之间互相访问数据的唯一方法 Android自身提供了一些常用的Provider audio、video、image、contacts等 如果你想使你的数据能够共享,要么建立一个你自己的ContentProvider;要么往已存在的ContentProvider中写数据,如何访问ContentProvider,借助工具类ContentResolver 获得ContentResolver 由activity或cont
2、ext的方法:getContentResolver() 使用ContentResolver的方法访问数据库 查找:query 插入:insert 更新:update 删除:delete,Content Provider如何存储数据,每一个Content Provider都有一个Uri来标识它本身 android.provider.Contacts.Phones.CONTENT_URI Content Provider存储数据的形式:,Content Provider的查找,final Cursor ContentResolver.query(Uri uri, String projection
3、, String selection, String selectionArgs, String sortOrder) 使用者自行管理Cursor的生命周期 final Cursor Activity.managedQuery(Uri uri, String projection, String selection, String selectionArgs, String sortOrder) 由所在的Activity来管理Cursor的生命周期,Content Provider的查找,String projection = new String People._ID, People._CO
4、UNT, People.NAME, People.NUMBER ; Uri contacts = People.CONTENT_URI; Cursor managedCursor = managedQuery(contacts, projection, / Which columns to return null, / Which rows to return (all rows) null, / Selection arguments (none) / Put the results in ascending order by name People.NAME + ASC);,Content
5、 Provider的查找,private void getColumnData(Cursor cur) if (cur.moveToFirst() String name, phoneNumber; int nameColumn = cur.getColumnIndex(People.NAME); int phoneColumn = cur.getColumnIndex(People.NUMBER); String imagePath; do name = cur.getString(nameColumn); phoneNumber = cur.getString(phoneColumn);
6、while (cur.moveToNext(); ,修改Content Provider的数据,增加一条新记录:insert 给一条已存在的记录增加新信息:insert 更新记录:update 删除记录:delete 借助:ContentValues、ContentResolver,增加一条新记录,ContentValues values = new ContentValues(); / Add Abraham Lincoln to contacts and make him a favorite. values.put(People.NAME, Abraham Lincoln); / 1 =
7、 the new contact is added to favorites / 0 = the new contact is not added to favorites values.put(People.STARRED, 1); Uri uri = getContentResolver().insert(People.CONTENT_URI, values);,已有记录增加新信息,Uri phoneUri = null; phoneUri = Uri.withAppendedPath(uri, People.Phones.CONTENT_DIRECTORY); values.clear(
8、); values.put(People.Phones.TYPE, People.Phones.TYPE_MOBILE); values.put(People.Phones.NUMBER, 1233214567); getContentResolver().insert(phoneUri, values);,更新和删除,更新: ContentResolver.update() 删除: ContentResolver.delete(),如何创建Content Provider?,通过Sqlite的方式建立ContentProvider 继承ContentProvider类 实现SQLiteOpenHelper 实现增删改查等接口 query insert update delete getType onCreate,如何创建Content Provider?,在manifest中声明ContentProvider ,The End!,