android中contentProvider及ContentResolver 野性酷女 2023-01-05 05:28 128阅读 0赞 前些天发现了一个巨牛的人工智能学习网站,通俗易懂,风趣幽默,忍不住分享一下给大家。[点击跳转到教程][Link 1] 这个技术是解决应用之间的一个调用,如常见的应用间数据库查询,内容提供者暴露接口,内容解析器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 package com.hbk.hbk_provider; import org.apache.http.client.utils.URIUtils; import android.content.ContentProvider; import android.content.ContentUris; import android.content.ContentValues; import android.content.UriMatcher; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.net.Uri; import android.util.Log; public class PersonProvider extends ContentProvider { private DbHelper dbHelper; private static UriMatcher matchers = new UriMatcher(UriMatcher.NO_MATCH); static{ matchers.addURI("com.hbk.hbk_provider.personprovider", "/person", 1); matchers.addURI("com.hbk.hbk_provider.personprovider", "/person/#", 2);//#匹配任意数字 } public PersonProvider() { Log.e("TAG", "PersonProvider()"); } @Override public boolean onCreate() { Log.e("TAG", "PersonProvider onCreate()"); dbHelper = new DbHelper(getContext()); return false; } /** * content://com.hbk.hbk_provider.personprovider/person 不根据id查询 * content://com.hbk.hbk_provider.personprovider/person/3 根据id查询 */ @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { SQLiteDatabase database = dbHelper.getReadableDatabase(); // 根据 int code = matchers.match(uri); if(code == 1){ //不根据id查询 // Cursor cursor = database.query("person", projection, selection, selectionArgs, null, null, null); return cursor; }else if(code == 2){ // 根据id查询 long id = ContentUris.parseId(uri); Cursor cursor = database.query("person", projection, "_id=?", new String[]{ id+""}, null, null, null); return cursor; }else{ throw new RuntimeException("查询的uri不合法"); } } @Override public String getType(Uri uri) { // TODO Auto-generated method stub return null; } /** * content://com.hbk.hbk_provider.personprovider/person 插入 * content://com.hbk.hbk_provider.personprovider/person/3 根据id插入(没有) */ @Override public Uri insert(Uri uri, ContentValues values) { SQLiteDatabase database = dbHelper.getReadableDatabase(); int code = matchers.match(uri); if(code == 1){ //不根据id查询 // long id = database.insert("person", null, values); uri = ContentUris.withAppendedId(uri, id); database.close(); return uri; }else { database.close(); throw new RuntimeException("插入的uri不合法"); } } /** * content://com.hbk.hbk_provider.personprovider/person 不根据id删除 * content://com.hbk.hbk_provider.personprovider/person/3 根据id删除 */ @Override public int delete(Uri uri, String selection, String[] selectionArgs) { SQLiteDatabase database = dbHelper.getReadableDatabase(); int code = matchers.match(uri); int deleteCount = -1; if(code == 1){ //不根据id删除 deleteCount = database.delete("person", selection, selectionArgs); }else if(code == 2){ long id = ContentUris.parseId(uri); deleteCount = database.delete("person", "_id="+id, null); }else{ database.close(); throw new RuntimeException("删除的uri不合法"); } database.close(); return deleteCount; } /** * content://com.hbk.hbk_provider.personprovider/person 不根据id更新 * content://com.hbk.hbk_provider.personprovider/person/3 根据id更新 */ @Override public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { SQLiteDatabase database = dbHelper.getReadableDatabase(); int code = matchers.match(uri); int updateCount = -1; if(code == 1){ //不根据id更新 updateCount = database.update("person", values, selection, selectionArgs); }else if(code == 2){ long id = ContentUris.parseId(uri); updateCount = database.update("person", values, "_id="+id, null); }else{ database.close(); throw new RuntimeException("更新的uri不合法"); } database.close(); return updateCount; } } 在清单文件中进行定义,exported为true表示允许其他营业进行调用,一般authorities的值为全类名小写,这个提供给内容解析器进行标识的字符串。 <provider android:name="com.hbk.hbk_provider.PersonProvider" android:authorities="com.hbk.hbk_provider.personprovider" android:exported="true"/> DbHelper.java常用的工具类 package com.hbk.hbk_provider; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.util.Log; public class DbHelper extends SQLiteOpenHelper { public DbHelper(Context context) { super(context, "huangbaokang.db", null,1); } @Override public void onCreate(SQLiteDatabase db) { Log.i("TAG","建表。。。"); db.execSQL("create table person(_id integer primary key autoincrement,name varchar)"); db.execSQL("insert into person(name) values('huangbaokang')"); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { } } 内容解析调用方android工程 布局 ![在这里插入图片描述][20210111211859334.png] <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:onClick="insert" android:text="INSERT" /> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:onClick="delete" android:text="DELETE" /> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:onClick="update" android:text="UPDATE" /> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:onClick="query" android:text="QUERY" /> </LinearLayout> 处理Activity package com.hbk.hbk_resolver; import android.app.Activity; import android.content.ContentResolver; import android.content.ContentValues; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.view.View; import android.widget.Toast; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } /* * 通过ContentResolver调用ContentProvider插入一条记录 */ public void insert(View v) { //1. 得到ContentResolver对象 ContentResolver resolver = getContentResolver(); //2. 调用其insert Uri uri = Uri.parse("content://com.hbk.hbk_provider.personprovider/person"); //uri = Uri.parse("content://com.hbk.hbk_provider.personprovider/person/3");//将抛异常 ContentValues values = new ContentValues(); values.put("name", "JACK"); uri = resolver.insert(uri, values); Toast.makeText(this, uri.toString(), 1).show(); } /* * 通过ContentResolver调用ContentProvider更新一条记录 */ public void update(View v) { //1. 得到ContentResolver对象 ContentResolver resolver = getContentResolver(); //2. 执行update Uri uri = Uri.parse("content://com.hbk.hbk_provider.personprovider/person/2"); ContentValues values = new ContentValues(); values.put("name", "JACK2"); int updateCount = resolver.update(uri, values, null, null); Toast.makeText(this, "updateCount="+updateCount, 1).show(); } /* * 通过ContentResolver调用ContentProvider删除一条记录 */ public void delete(View v) { //1. 得到ContentResolver对象 ContentResolver resolver = getContentResolver(); //2. 执行delete Uri uri = Uri.parse("content://com.hbk.hbk_provider.personprovider/person/2"); int deleteCount = resolver.delete(uri, null, null); Toast.makeText(this, "deleteCount="+deleteCount, 1).show(); } public void query(View v){ ContentResolver contentResolver = getContentResolver(); //2. 调用其query, 得到cursor Uri uri = Uri.parse("content://com.hbk.hbk_provider.personprovider/person"); Cursor cursor = contentResolver.query(uri, null, null, null, null); while(cursor.moveToNext()){ int id = cursor.getInt(0); String name = cursor.getString(1); Toast.makeText(this, "id="+id+" name="+name, 0).show(); } cursor.close(); } } 工程架构 ![在这里插入图片描述][20210111212027978.png] 欢迎加入康哥IT粉丝交流QQ群833249482 ![在这里插入图片描述][20210511091712437.png_pic_center] [Link 1]: https://www.captainai.net/flyop007/ [20210111211859334.png]: /images/20221119/902b6ec347234cad86346f58918b56c4.png [20210111212027978.png]: /images/20221119/e04fe2caaa194db5971aa7afd87d6b29.png [20210511091712437.png_pic_center]: https://img-blog.csdnimg.cn/20210511091712437.png#pic_center
还没有评论,来说两句吧...