我的android 第24天 - ContentUris和ContentProvider

我的android 第24天 -  ContentUris和ContentProvider

ContentUris类使用介绍

      ContentUris类用于获取Uri路径后面的ID部分,它有两个比较实用的方法:

withAppendedId(uri, id)用于为路径加上ID部分:

  Uriuri = Uri.parse("content://cn.itcast.provider.personprovider/person")

UriresultUri = ContentUris.withAppendedId(uri,10);

//生成后的Ur为:content://cn.itcast.provider.personprovider/person/10

parseId(uri)方法用于从路径中获取ID部分:

Uriuri Uri.parse("content://cn.itcast.provider.personprovider/person/10")

longpersonid  ContentUris.parseId(uri);//获取的结果为:10

使用ContentProvider共享数据

ContentProvider类主要方法的作用:

publicboolean onCreate()

该方法在ContentProvider创建后就会被调用, Android开机后, ContentProvider在其它应用第一次访问它时才会被创建。

publicUri insert(Uri uri, ContentValuesvalues)

该方法用于供外部应用往ContentProvider添加数据。

publicintdelete(Uri uri,String selection, String[] selectionArgs)

该方法用于供外部应用从ContentProvider删除数据。

publicintupdate(Uri uri, ContentValuesvalues, String selection, String[] selectionArgs)

该方法用于供外部应用更新ContentProvider中的数据。

publicCursor query(Uri uri,String[] projection, String selection, String[] selectionArgs,String sortOrder)

该方法用于供外部应用从ContentProvider中获取数据。

publicString getType(Uri uri)

该方法用于返回当前Url所代表数据的MIME类型。如果操作的数据属于集合类型,那么MIME类型字符串应该以vnd.android.cursor.dir/开头,例如:要得到所有person记录的Uri为content://cn.itcast.provider.personprovider/person,那么返回的MIME类型字符串应该为:“vnd.android.cursor.dir/person”。如果要操作的数据属于非集合类型数据,那么MIME类型字符串应该以vnd.android.cursor.item/开头,例如:得到id为10的person记录,Uri为content://cn.itcast.provider.personprovider/person/10,那么返回的MIME类型字符串应该为:“vnd.android.cursor.item/person”。



下载视频代码

### AndroidContentProvider 的使用指南 #### 什么是 ContentProvider? `ContentProvider` 是一种用于管理共享数据的组件,它允许应用程序之间交换数据。通过 `ContentProvider`,可以实现跨应用的数据读取写入操作[^1]。 --- #### ContentProvider 的基本工作原理 当一个应用需要访问另一个应用中的数据时,通常会通过 `ContentResolver` 发起请求。这些请求会被转发到目标应用中的 `ContentProvider`,由其执行具体的逻辑并返回结果给调用方。这种机制使得不同应用之间的交互更加安全标准化。 --- #### 创建自定义 ContentProvider 的步骤 以下是创建使用 `ContentProvider` 的核心流程: ##### 1. 定义 URI MIME 类型 为了唯一标识数据表或记录集合,必须定义相应的 URI 格式。例如,在 Android NDK 开发中,URI 可能如下所示: ```plaintext content://com.example.provider/table1/vnd.android.cursor.dir/vnd.com.example.provider.table1 ``` 其中,“`vnd.android.cursor.dir/...`” 表示这是一个目录类型的资源[^2]。 ##### 2. 继承 ContentProvider 并重写必需方法 在继承 `android.content.ContentProvider` 后,需实现以下五个主要方法: - **onCreate()**: 初始化 Provider。 - **query(Uri, String[], String, String[], String)**: 查询数据。 - **insert(Uri, ContentValues)**: 插入新记录。 - **update(Uri, ContentValues, String, String[])**: 更新现有记录。 - **delete(Uri, String, String[])**: 删除指定记录。 - **getType(Uri)**: 返回对应 URI 的 MIME 类型。 下面是一个简单的例子: ```java public class MyContentProvider extends ContentProvider { public static final String AUTHORITY = "com.example.myprovider"; private SQLiteDatabase database; @Override public boolean onCreate() { // 初始化数据库或其他资源 DatabaseHelper dbHelper = new DatabaseHelper(getContext()); this.database = dbHelper.getWritableDatabase(); return true; } @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { // 处理查询请求 SQLiteQueryBuilder builder = new SQLiteQueryBuilder(); builder.setTables("table_name"); Cursor cursor = builder.query(database, projection, selection, selectionArgs, null, null, sortOrder); cursor.setNotificationUri(getContext().getContentResolver(), uri); return cursor; } @Override public Uri insert(Uri uri, ContentValues values) { long rowId = database.insert("table_name", "", values); if (rowId > 0) { Uri insertedUri = ContentUris.withAppendedId(uri, rowId); getContext().getContentResolver().notifyChange(insertedUri, null); return insertedUri; } throw new SQLException("Failed to add a record into " + uri); } @Override public int delete(Uri uri, String selection, String[] selectionArgs) { int count = database.delete("table_name", selection, selectionArgs); getContext().getContentResolver().notifyChange(uri, null); return count; } @Override public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { int count = database.update("table_name", values, selection, selectionArgs); getContext().getContentResolver().notifyChange(uri, null); return count; } @Override public String getType(Uri uri) { switch (uriMatcher.match(uri)) { case CODE_DIR: return "vnd.android.cursor.dir/vnd." + AUTHORITY + ".table_name"; case CODE_ITEM: return "vnd.android.cursor.item/vnd." + AUTHORITY + ".table_name"; default: throw new IllegalArgumentException("Unsupported URI: " + uri); } } } ``` 上述代码展示了如何构建一个基础的 `ContentProvider` 来支持 CRUD 操作。 --- #### 注册 ContentProvider 要在项目中注册该提供者,需要修改 `AndroidManifest.xml` 文件,添加 `<provider>` 节点: ```xml <application> ... <provider android:name=".MyContentProvider" android:authorities="com.example.myprovider" android:exported="true"/> </application> ``` 这里的 `android:authorities` 属性指定了唯一的授权名称,而 `android:exported=true` 则表示此提供者可被外部应用访问。 --- #### 使用 ContentResolver 访问数据 假设有一个 Activity 需要从远程服务获取某些参数,则可通过以下方式完成: ```java Intent intent = getIntent(); String extraData = intent.getStringExtra("extra_data"); // 构造 URI 对象 Uri contentUri = Uri.parse("content://com.example.myprovider/table_name"); // 获取 ContentResolver 实例 ContentResolver resolver = getContentResolver(); // 执行查询操作 Cursor cursor = resolver.query(contentUri, null, null, null, null); if (cursor != null && cursor.moveToFirst()) { do { String columnValue = cursor.getString(cursor.getColumnIndexOrThrow("column_name")); Log.d("ContentProviderExample", "Fetched Value: " + columnValue); } while (cursor.moveToNext()); cursor.close(); } else { Log.e("ContentProviderExample", "No data found or error occurred."); } ``` 以上片段说明了如何利用 `ContentResolver` 进行跨进程通信以及提取所需字段[^3]。 --- #### 常见问题排查 如果遇到无法正常连接至目标 `ContentProvider` 或接收不到预期响应的情况,请检查以下几个方面: 1. 是否正确配置了 `manifests` 文件内的 provider 设置; 2. 数据库初始化过程是否存在异常; 3. 提供者的 authority 字符串是否匹配实际需求; 4. 网络权限或者文件路径设置是否有误(针对涉及敏感信息的操作)。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值