ContentProvider 被访问的(一)
2016-06-21 00:39
411 查看
提供数据被访问的一方。
public class WordProvider extends ContentProvider { private UriMatcher matcher; private static final int MATCH_ROOT = 1; private static final int MATCH_HELLO = 2; @Override public boolean onCreate() { // 当本ContentProvider被创建时回调 // 第一步,创建UriMatcher对象 matcher = new UriMatcher(UriMatcher.NO_MATCH); // 第二步,添加匹配的URI,并指定匹配时的返回值 //MATCH_ROOT MATCH_HELLO 就是返回值 matcher.addURI("cn.teee.providers.word", null, MATCH_ROOT); matcher.addURI("cn.teee.providers.word", "hello", MATCH_HELLO); return false; } // content://cn.teee.providers.word // content://cn.teee.providers.word/hello @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { // 当其它应用查询数据时回调 //第三步,与已经注册的URI进行匹配 switch (matcher.match(uri)) { //根据返回值做判断 case MATCH_ROOT: DBOpenHelper dbOpenHelper = new DBOpenHelper(getContext()); SQLiteDatabase db = dbOpenHelper.getWritableDatabase(); Cursor c = db.query("word", projection, selection, selectionArgs, null, null, sortOrder); return c; default: throw new RuntimeException("非法的Uri -> " + uri); } } @Override public Uri insert(Uri uri, ContentValues values) { // 当其它应用添加数据时回调 // 验证Uri //第三步,与已经注册的URI进行匹配 int code = matcher.match(uri); Log.d("teee", "uri -> " + uri.toString()); switch (code) { //根据返回值做判断 case MATCH_ROOT: Log.d("teee", "MATCH_ROOT"); DBOpenHelper dbOpenHelper = new DBOpenHelper(getContext()); SQLiteDatabase db = dbOpenHelper.getWritableDatabase(); long id = db.insert("word", null, values); if (db.isOpen()) { db.close(); db = null; } // content://cn.teee.providers.word/13 return ContentUris.withAppendedId(uri, id); case MATCH_HELLO: Log.d("teee", "MATCH_HELLO"); throw new RuntimeException("非法的Uri:" + uri); case UriMatcher.NO_MATCH: Log.d("teee", "NO_MATCH"); throw new RuntimeException("非法的Uri:" + uri); } return null; } @Override public int delete(Uri uri, String selection, String[] selectionArgs) { // 当其它应用删除数据时回调 return 0; } @Override public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { // 当其它应用修改数据时回调 // -- 假设不提供修改数据的服务 -- throw new RuntimeException("不允许修改数据!!!"); } @Override public String getType(Uri uri) { // (无视) return null; } }
相关文章推荐
- asp Driver和Provider两种连接字符串连接Access时的区别
- 错误类型:Provider (0x80004005)未指定的错误 的一个处理方法
- 基于Android ContentProvider的总结详解
- Provider错误80004005终极解决方法(完全有效的方法)
- Android 自定义Prodvider
- $provide里的provider方法
- AngularJS中service,factory,provider的区别
- Android 学习笔记 Contacts (一)ContentResolver query 参数详解
- 安卓provider 的注意事项
- credential Provider 简易改写攻略
- AngularJS中service,factory,provider的区别
- android--Content Provider 你应该记住的一些事-1
- sunPKCS11
- Android中Action Bar的使用
- Android_RxJava+ContentObserver
- Android入门——内容提供者Content Provider详解与应用
- OLE DB provider "SQLNCLI11" for linked server "dbLink01" was unable to begin a distributed transac
- ContentProvider应用组件实例记录
- .NET连接SQL Server的问题处理
- ShareActionProvider 分享API之 DynamicShareActionProvider