android中contentProvider及ContentResolver

野性酷女 2023-01-05 05:28 245阅读 0赞

前些天发现了一个巨牛的人工智能学习网站,通俗易懂,风趣幽默,忍不住分享一下给大家。点击跳转到教程
这个技术是解决应用之间的一个调用,如常见的应用间数据库查询,内容提供者暴露接口,内容解析器ContentResolver通过调用相应CRUD接口,内容提供者需要在清单文件进行定义。
案例:
我们新建一个PersonProvider继承ContentProvider,并在CRUD实现上借助Sqlite工具类进行操作。
这个同时需要理解一些理论性的知识,如URI的格式content://com.hbk.hbk_provider.personprovider/person/3
调用的URI是否合法,用到的相关API,有
UriMatcher.addURI(String authority, String path, int code) // 添加合法URI
int android.content.UriMatcher.match(Uri uri)// 判断Uri是否合法
long android.content.ContentUris.parseId(Uri contentUri)// 提取uri的id
Uri ContentUris.withAppendedId(Uri contentUri, long id)// 这个一般用在插入,使得插入后的Uri有id值

PersonProvider.java

  1. package com.hbk.hbk_provider;
  2. import org.apache.http.client.utils.URIUtils;
  3. import android.content.ContentProvider;
  4. import android.content.ContentUris;
  5. import android.content.ContentValues;
  6. import android.content.UriMatcher;
  7. import android.database.Cursor;
  8. import android.database.sqlite.SQLiteDatabase;
  9. import android.net.Uri;
  10. import android.util.Log;
  11. public class PersonProvider extends ContentProvider {
  12. private DbHelper dbHelper;
  13. private static UriMatcher matchers = new UriMatcher(UriMatcher.NO_MATCH);
  14. static{
  15. matchers.addURI("com.hbk.hbk_provider.personprovider", "/person", 1);
  16. matchers.addURI("com.hbk.hbk_provider.personprovider", "/person/#", 2);//#匹配任意数字
  17. }
  18. public PersonProvider() {
  19. Log.e("TAG", "PersonProvider()");
  20. }
  21. @Override
  22. public boolean onCreate() {
  23. Log.e("TAG", "PersonProvider onCreate()");
  24. dbHelper = new DbHelper(getContext());
  25. return false;
  26. }
  27. /** * content://com.hbk.hbk_provider.personprovider/person 不根据id查询 * content://com.hbk.hbk_provider.personprovider/person/3 根据id查询 */
  28. @Override
  29. public Cursor query(Uri uri, String[] projection, String selection,
  30. String[] selectionArgs, String sortOrder) {
  31. SQLiteDatabase database = dbHelper.getReadableDatabase();
  32. // 根据
  33. int code = matchers.match(uri);
  34. if(code == 1){ //不根据id查询
  35. //
  36. Cursor cursor = database.query("person", projection, selection, selectionArgs, null, null, null);
  37. return cursor;
  38. }else if(code == 2){
  39. // 根据id查询
  40. long id = ContentUris.parseId(uri);
  41. Cursor cursor = database.query("person", projection, "_id=?", new String[]{ id+""}, null, null, null);
  42. return cursor;
  43. }else{
  44. throw new RuntimeException("查询的uri不合法");
  45. }
  46. }
  47. @Override
  48. public String getType(Uri uri) {
  49. // TODO Auto-generated method stub
  50. return null;
  51. }
  52. /** * content://com.hbk.hbk_provider.personprovider/person 插入 * content://com.hbk.hbk_provider.personprovider/person/3 根据id插入(没有) */
  53. @Override
  54. public Uri insert(Uri uri, ContentValues values) {
  55. SQLiteDatabase database = dbHelper.getReadableDatabase();
  56. int code = matchers.match(uri);
  57. if(code == 1){ //不根据id查询
  58. //
  59. long id = database.insert("person", null, values);
  60. uri = ContentUris.withAppendedId(uri, id);
  61. database.close();
  62. return uri;
  63. }else {
  64. database.close();
  65. throw new RuntimeException("插入的uri不合法");
  66. }
  67. }
  68. /** * content://com.hbk.hbk_provider.personprovider/person 不根据id删除 * content://com.hbk.hbk_provider.personprovider/person/3 根据id删除 */
  69. @Override
  70. public int delete(Uri uri, String selection, String[] selectionArgs) {
  71. SQLiteDatabase database = dbHelper.getReadableDatabase();
  72. int code = matchers.match(uri);
  73. int deleteCount = -1;
  74. if(code == 1){ //不根据id删除
  75. deleteCount = database.delete("person", selection, selectionArgs);
  76. }else if(code == 2){
  77. long id = ContentUris.parseId(uri);
  78. deleteCount = database.delete("person", "_id="+id, null);
  79. }else{
  80. database.close();
  81. throw new RuntimeException("删除的uri不合法");
  82. }
  83. database.close();
  84. return deleteCount;
  85. }
  86. /** * content://com.hbk.hbk_provider.personprovider/person 不根据id更新 * content://com.hbk.hbk_provider.personprovider/person/3 根据id更新 */
  87. @Override
  88. public int update(Uri uri, ContentValues values, String selection,
  89. String[] selectionArgs) {
  90. SQLiteDatabase database = dbHelper.getReadableDatabase();
  91. int code = matchers.match(uri);
  92. int updateCount = -1;
  93. if(code == 1){ //不根据id更新
  94. updateCount = database.update("person", values, selection, selectionArgs);
  95. }else if(code == 2){
  96. long id = ContentUris.parseId(uri);
  97. updateCount = database.update("person", values, "_id="+id, null);
  98. }else{
  99. database.close();
  100. throw new RuntimeException("更新的uri不合法");
  101. }
  102. database.close();
  103. return updateCount;
  104. }
  105. }

在清单文件中进行定义,exported为true表示允许其他营业进行调用,一般authorities的值为全类名小写,这个提供给内容解析器进行标识的字符串。

  1. <provider android:name="com.hbk.hbk_provider.PersonProvider" android:authorities="com.hbk.hbk_provider.personprovider" android:exported="true"/>

DbHelper.java常用的工具类

  1. package com.hbk.hbk_provider;
  2. import android.content.Context;
  3. import android.database.sqlite.SQLiteDatabase;
  4. import android.database.sqlite.SQLiteOpenHelper;
  5. import android.util.Log;
  6. public class DbHelper extends SQLiteOpenHelper {
  7. public DbHelper(Context context) {
  8. super(context, "huangbaokang.db", null,1);
  9. }
  10. @Override
  11. public void onCreate(SQLiteDatabase db) {
  12. Log.i("TAG","建表。。。");
  13. db.execSQL("create table person(_id integer primary key autoincrement,name varchar)");
  14. db.execSQL("insert into person(name) values('huangbaokang')");
  15. }
  16. @Override
  17. public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
  18. }
  19. }

内容解析调用方android工程
布局
在这里插入图片描述

  1. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" >
  2. <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:onClick="insert" android:text="INSERT" />
  3. <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:onClick="delete" android:text="DELETE" />
  4. <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:onClick="update" android:text="UPDATE" />
  5. <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:onClick="query" android:text="QUERY" />
  6. </LinearLayout>

处理Activity

  1. package com.hbk.hbk_resolver;
  2. import android.app.Activity;
  3. import android.content.ContentResolver;
  4. import android.content.ContentValues;
  5. import android.database.Cursor;
  6. import android.net.Uri;
  7. import android.os.Bundle;
  8. import android.view.View;
  9. import android.widget.Toast;
  10. public class MainActivity extends Activity {
  11. @Override
  12. protected void onCreate(Bundle savedInstanceState) {
  13. super.onCreate(savedInstanceState);
  14. setContentView(R.layout.activity_main);
  15. }
  16. /* * 通过ContentResolver调用ContentProvider插入一条记录 */
  17. public void insert(View v) {
  18. //1. 得到ContentResolver对象
  19. ContentResolver resolver = getContentResolver();
  20. //2. 调用其insert
  21. Uri uri = Uri.parse("content://com.hbk.hbk_provider.personprovider/person");
  22. //uri = Uri.parse("content://com.hbk.hbk_provider.personprovider/person/3");//将抛异常
  23. ContentValues values = new ContentValues();
  24. values.put("name", "JACK");
  25. uri = resolver.insert(uri, values);
  26. Toast.makeText(this, uri.toString(), 1).show();
  27. }
  28. /* * 通过ContentResolver调用ContentProvider更新一条记录 */
  29. public void update(View v) {
  30. //1. 得到ContentResolver对象
  31. ContentResolver resolver = getContentResolver();
  32. //2. 执行update
  33. Uri uri = Uri.parse("content://com.hbk.hbk_provider.personprovider/person/2");
  34. ContentValues values = new ContentValues();
  35. values.put("name", "JACK2");
  36. int updateCount = resolver.update(uri, values, null, null);
  37. Toast.makeText(this, "updateCount="+updateCount, 1).show();
  38. }
  39. /* * 通过ContentResolver调用ContentProvider删除一条记录 */
  40. public void delete(View v) {
  41. //1. 得到ContentResolver对象
  42. ContentResolver resolver = getContentResolver();
  43. //2. 执行delete
  44. Uri uri = Uri.parse("content://com.hbk.hbk_provider.personprovider/person/2");
  45. int deleteCount = resolver.delete(uri, null, null);
  46. Toast.makeText(this, "deleteCount="+deleteCount, 1).show();
  47. }
  48. public void query(View v){
  49. ContentResolver contentResolver = getContentResolver();
  50. //2. 调用其query, 得到cursor
  51. Uri uri = Uri.parse("content://com.hbk.hbk_provider.personprovider/person");
  52. Cursor cursor = contentResolver.query(uri, null, null, null, null);
  53. while(cursor.moveToNext()){
  54. int id = cursor.getInt(0);
  55. String name = cursor.getString(1);
  56. Toast.makeText(this, "id="+id+" name="+name, 0).show();
  57. }
  58. cursor.close();
  59. }
  60. }

工程架构
在这里插入图片描述
欢迎加入康哥IT粉丝交流QQ群833249482
在这里插入图片描述

发表评论

表情:
评论列表 (有 0 条评论,245人围观)

还没有评论,来说两句吧...

相关阅读