android之内容提供者解析

该系统有两个应用,比较繁琐。但是内容提供者是android里非常非常重要的一个内容,我们得好好学习下哦。先看效果图,我们提供了四个按钮,点击按钮便会进行相应的操作。

我们先看内容提供者所在的应用,代码结构:

activity代码:

  1. package cn.com.contentProvider;  
  2.   
  3. import android.app.Activity;  
  4. import android.os.Bundle;  
  5. import android.widget.TextView;  
  6.   
  7. public class ContentProviderAcitivity extends Activity {  
  8.     @Override  
  9.     public void onCreate(Bundle savedInstanceState) {  
  10.         super.onCreate(savedInstanceState);  
  11.         setContentView(R.layout.main);  
  12.        
  13.     }  
  14. }  

MyContentProvider.java代码

  1. package cn.com.contentProvider;  
  2.   
  3. import android.content.ContentProvider;  
  4. import android.content.ContentUris;  
  5. import android.content.ContentValues;  
  6. import android.content.Context;  
  7. import android.content.UriMatcher;  
  8. import android.database.Cursor;  
  9. import android.database.sqlite.SQLiteDatabase;  
  10. import android.database.sqlite.SQLiteOpenHelper;  
  11. import android.database.sqlite.SQLiteDatabase.CursorFactory;  
  12. import android.net.Uri;  
  13.   
  14. /** 
  15.  *  
  16.  * @author chenzheng_java 
  17.  * @description 自定义的内容提供者. 
  18.  *  总结下访问内容提供者的主要步骤: 
  19.  * 第一:我们要有一个uri,这就相当于我们的网址,我们有了网址才能去访问具体的网站 
  20.  * 第二:我们去系统中寻找该uri中的authority(可以理解为主机地址), 
  21.  *      只要我们的内容提供者在manifest.xml文件中注册了,那么系统中就一定存在。 
  22.  * 第三:通过内容提供者内部的uriMatcher对请求进行验证(你找到我了,还不行,我还得看看你有没有权限访问我呢)。 
  23.  * 第四:验证通过后,就可以调用内容提供者的增删查改方法进行操作了 
  24.  */  
  25. public class MyContentProvider extends ContentProvider {  
  26.     // 自己实现的数据库操作帮助类  
  27.     private MyOpenHelper myOpenHelper;  
  28.   
  29.     // 数据库相关类  
  30.     private SQLiteDatabase sqLiteDatabase;  
  31.   
  32.     // uri匹配相关  
  33.     private static UriMatcher uriMatcher;  
  34.   
  35.     // 主机名称(这一部分是可以随便取得)  
  36.     private static final String authority = "cn.com.chenzheng_java.hello";  
  37.   
  38.     // 注册该内容提供者匹配的uri  
  39.     static {  
  40.         uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);  
  41.         /* 
  42.          * path_chenzheng部分的字符串是随便取得,1代表着如果请求的uri与当前加入 
  43.          * 的匹配uri正好吻合,uriMathcher.match()方法返回的值.#代表任意数字,*代表任意字符串 
  44.          */  
  45.         uriMatcher.addURI(authority, "path_chenzheng", 1);// 代表当前表中的所有的记录  
  46.         uriMatcher.addURI(authority, "path_chenzheng/#", 2);// 代表当前表中的某条特定的记录,记录id便是#处得数字  
  47.     }  
  48.   
  49.     // 数据表中的列名映射  
  50.     private static final String _id = "id";  
  51.     private static final String name = "name";  
  52.     private static final String age = "age";  
  53.     private static final String isMan = "isMan";  
  54.   
  55.     /** 
  56.      * @description 当内容提供者第一次创建时执行 
  57.      */  
  58.     @Override  
  59.     public boolean onCreate() {  
  60.         try {  
  61.             myOpenHelper = new MyOpenHelper(getContext(), DB_Name, null,  
  62.                     Version_1);  
  63.   
  64.         } catch (Exception e) {  
  65.   
  66.             return false;  
  67.         }  
  68.         return true;  
  69.     }  
  70.   
  71.     /** 
  72.      * @description 对数据库进行删除操作的时候执行 
  73.      *              android.content.ContentUri为我们解析uri相关的内容提供了快捷方便的途径 
  74.      */  
  75.     @Override  
  76.     public int delete(Uri uri, String selection, String[] selectionArgs) {  
  77.         int number = 0;  
  78.         sqLiteDatabase = myOpenHelper.getWritableDatabase();  
  79.         int code = uriMatcher.match(uri);  
  80.         switch (code) {  
  81.         case 1:  
  82.             number = sqLiteDatabase  
  83.                     .delete(Table_Name, selection, selectionArgs);  
  84.             break;  
  85.         case 2:  
  86.             long id = ContentUris.parseId(uri);  
  87.             /* 
  88.              * 拼接where子句用三目运算符是不是特烦人啊? 实际上,我们这里可以用些技巧的. 
  89.              * if(selection==null||"".equals(selection.trim())) selection = 
  90.              * " 1=1 and "; selection+=_id+"="+id; 
  91.              * 拼接where子句中最麻烦的就是and的问题,这里我们通过添加一个1=1这样的恒等式便将问题解决了 
  92.              */  
  93.             selection = (selection == null || "".equals(selection.trim())) ? _id  
  94.                     + "=" + id  
  95.                     : selection + " and " + _id + "=" + id;  
  96.             number = sqLiteDatabase  
  97.                     .delete(Table_Name, selection, selectionArgs);  
  98.             break;  
  99.         default:  
  100.             throw new IllegalArgumentException("异常参数");  
  101.         }  
  102.   
  103.         return number;  
  104.     }  
  105.   
  106.     /** 
  107.      *@description 获取当前内容提供者的MIME类型 集合类型必须添加前缀vnd.android.cursor.dir/(该部分随意) 
  108.      *              单条记录类型添加前缀vnd,android.cursor.item/(该部分随意) 
  109.      *              定义了该方法之后,系统会在第一次请求时进行验证,验证通过则执行crub方法时不再重复进行验证, 
  110.      *              否则如果没有定义该方法或者验证失败,crub方法执行的时候系统会默认的为其添加类型验证代码。 
  111.      */  
  112.     @Override  
  113.     public String getType(Uri uri) {  
  114.         int code = uriMatcher.match(uri);  
  115.         switch (code) {  
  116.         case 1:  
  117.             return "vnd.android.cursor.dir/chenzheng_java";  
  118.         case 2:  
  119.             return "vnd.android.cursor.item/chenzheng_java";  
  120.         default:  
  121.             throw new IllegalArgumentException("异常参数");  
  122.         }  
  123.   
  124.     }  
  125.   
  126.     /** 
  127.      * @description 对数据表进行insert时执行该方法 
  128.      */  
  129.     @Override  
  130.     public Uri insert(Uri uri, ContentValues values) {  
  131.         sqLiteDatabase = myOpenHelper.getWritableDatabase();  
  132.         int code = uriMatcher.match(uri);  
  133.         switch (code) {  
  134.         case 1:  
  135.             sqLiteDatabase.insert(Table_Name, name, values);  
  136.             break;  
  137.         case 2:  
  138.             long id = sqLiteDatabase.insert(Table_Name, name, values);  
  139.             // withAppendId将id添加到uri的最后  
  140.             ContentUris.withAppendedId(uri, id);  
  141.             break;  
  142.         default:  
  143.             throw new IllegalArgumentException("异常参数");  
  144.         }  
  145.   
  146.         return uri;  
  147.     }  
  148.   
  149.     /** 
  150.      * 当执行查询时调用该方法 
  151.      */  
  152.     @Override  
  153.     public Cursor query(Uri uri, String[] projection, String selection,  
  154.             String[] selectionArgs, String sortOrder) {  
  155.         Cursor cursor = null;  
  156.         sqLiteDatabase = myOpenHelper.getReadableDatabase();  
  157.         int code = uriMatcher.match(uri);  
  158.         switch (code) {  
  159.         case 1:  
  160.             cursor = sqLiteDatabase.query(Table_Name, projection, selection,  
  161.                     selectionArgs, null, null, sortOrder);  
  162.             break;  
  163.         case 2:  
  164.             // 从uri中解析出ID  
  165.             long id = ContentUris.parseId(uri);  
  166.             selection = (selection == null || "".equals(selection.trim())) ? _id  
  167.                     + "=" + id  
  168.                     : selection + " and " + _id + "=" + id;  
  169.             cursor = sqLiteDatabase.query(Table_Name, projection, selection,  
  170.                     selectionArgs, null, null, sortOrder);  
  171.             break;  
  172.         default:  
  173.             throw new IllegalArgumentException("参数错误");  
  174.         }  
  175.   
  176.         return cursor;  
  177.     }  
  178.   
  179.     /** 
  180.      * 当执行更新操作的时候执行该方法 
  181.      */  
  182.     @Override  
  183.     public int update(Uri uri, ContentValues values, String selection,  
  184.             String[] selectionArgs) {  
  185.         int num = 0;  
  186.         sqLiteDatabase = myOpenHelper.getWritableDatabase();  
  187.         int code = uriMatcher.match(uri);  
  188.         switch (code) {  
  189.         case 1:  
  190.             num = sqLiteDatabase.update(Table_Name, values, selection, selectionArgs);  
  191.             break;  
  192.         case 2:  
  193.             long id = ContentUris.parseId(uri);  
  194.             selection = (selection == null || "".equals(selection.trim())) ? _id  
  195.                     + "=" + id  
  196.                     : selection + " and " + _id + "=" + id;  
  197.             num = sqLiteDatabase.update(Table_Name, values, selection, selectionArgs);  
  198.             break;  
  199.         default:  
  200.             break;  
  201.         }  
  202.         return num;  
  203.     }  
  204.   
  205.     // 数据库名称  
  206.     private final String DB_Name = "chenzheng_java.db";  
  207.     // 数据表名  
  208.     private final String Table_Name = "chenzheng_java";  
  209.     // 版本号  
  210.     private final int Version_1 = 1;  
  211.   
  212.     private class MyOpenHelper extends SQLiteOpenHelper {  
  213.   
  214.         public MyOpenHelper(Context context, String name,  
  215.                 CursorFactory factory, int version) {  
  216.             super(context, name, factory, version);  
  217.         }  
  218.   
  219.         /** 
  220.          * @description 当数据表无连接时创建新的表 
  221.          */  
  222.         @Override  
  223.         public void onCreate(SQLiteDatabase db) {  
  224.             String sql = " create table if not exists " + Table_Name  
  225.                     + "(id INTEGER,name varchar(20),age integer,isMan boolean)";  
  226.             db.execSQL(sql);  
  227.         }  
  228.   
  229.         /** 
  230.          * @description 当版本更新时触发的方法 
  231.          */  
  232.         @Override  
  233.         public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {  
  234.             String sql = " drop table if exists " + Table_Name;  
  235.             db.execSQL(sql);  
  236.             onCreate(db);  
  237.         }  
  238.   
  239.     }  
  240. }  

androidManifest.xml代码

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     package="cn.com.contentProvider" android:versionCode="1"  
  4.     android:versionName="1.0">  
  5.     <uses-sdk android:minSdkVersion="8" />  
  6.   
  7.     <application android:icon="@drawable/icon" android:label="@string/app_name">  
  8.         <activity android:name=".ContentProviderAcitivity"  
  9.             android:label="@string/app_name">  
  10.             <intent-filter>  
  11.                 <action android:name="android.intent.action.MAIN" />  
  12.                 <category android:name="android.intent.category.LAUNCHER" />  
  13.             </intent-filter>  
  14.         </activity>  
  15.         <provider android:name=".MyContentProvider"  
  16.             android:authorities="cn.com.chenzheng_java.hello"  
  17.             android:multiprocess="true" android:permission="cn.com.chenzheng_java.permission"></provider>  
  18.     </application>  
  19.     <!--   
  20.         permission中的android:name的值与provider中的android:permission的值是一样的  
  21.         android:protectionLevel 则代表了权限等级  
  22.      -->  
  23.     <permission android:name="cn.com.chenzheng_java.permission"  
  24.         android:protectionLevel="normal"></permission>  
  25.   
  26. </manifest>  

main.xml为默认。

----------------------------------------------------------------------------------------------------------------

第二个应用(用于访问内容提供者的应用)

activity代码

  1. package cn.com.chenzheng_java;  
  2.   
  3. import android.app.Activity;  
  4. import android.content.ContentResolver;  
  5. import android.content.ContentValues;  
  6. import android.database.Cursor;  
  7. import android.net.Uri;  
  8. import android.os.Bundle;  
  9. import android.util.Log;  
  10. import android.view.View;  
  11. import android.widget.Button;  
  12. import android.widget.TextView;  
  13. /** 
  14.  *  
  15.  * @author chenzheng_java 
  16.  * @description 通过访问内容提供者进行增删查改.注意本程序中为了方便阅读, 
  17.  * 在需要数据库列名的地方直接写上了数据库中字段的名称,实际上这是不合理的, 
  18.  * 作为内容提供者的使用者,我们不可能在使用这个内容提供者之前先去了解sqlite 
  19.  * 中表的结构。比较适宜的做法是,在内容提供者中将愿意提供给外部访问的字段名称(列名) 
  20.  * 定义为string final 的常量! 
  21.  */  
  22. public class ContentAccessActivity extends Activity {  
  23.     private final static String tag = "通知";  
  24.     private TextView textView;  
  25.     String result = "结果:/n";  
  26.     ContentResolver reslover;  
  27.     Uri uri;  
  28.   
  29.     @Override  
  30.     public void onCreate(Bundle savedInstanceState) {  
  31.         super.onCreate(savedInstanceState);  
  32.         setContentView(R.layout.main);  
  33.         /** 
  34.          * 这里我们一定要搞清楚,uri的内容到底和内容提供者中哪个地方一一对应 
  35.          * 在MyContentProvider中我们有如下片段 
  36.          * uriMatcher.addURI(authority, "path_chenzheng", 1);// 代表当前表中的所有的记录 
  37.         uriMatcher.addURI(authority, "path_chenzheng/#", 2);// 代表当前表中的某条特定的记录,记录id便是#处得数字 
  38.         其中authority为cn.com.chenzheng_java.hello。 
  39.          */  
  40.         uri = Uri.parse("content://cn.com.chenzheng_java.hello/path_chenzheng");  
  41.           
  42.         /** 
  43.          * 内容提供者是什么?内容提供者相当于一个封装好了增删改查操作的接口,这个接口有一把锁,只有携带钥匙的访问者才能访问。 
  44.          * ContentResolver是什么?ContentResolver是一个开锁匠,他携带者钥匙(钥匙上有标签显示他是那个门得钥匙,如path_chenzheng) 
  45.          * 去寻找内容提供者,然后访问内容提供者的增删查改方法 
  46.          * 我们这里调用contentResolver的增删查改就相当于将任务交给了锁匠, 
  47.          * 然后让锁匠去找能打开的内容提供者,并且执行里面相应的方法,并将结果返回. 
  48.          * ContentResolver的好处在于,我们可以无视CotentProvider的具体实现,无论contentProvider里面是如何实现的,我想执行 
  49.          * 某一个操作时,所要书写的代码都是一样的。 
  50.          */  
  51.         reslover = this.getContentResolver();  
  52.         textView = (TextView) findViewById(R.id.textView);  
  53.   
  54.         Button insertButton = (Button) findViewById(R.id.insertButton);  
  55.         insertButton.setOnClickListener(new View.OnClickListener() {  
  56.             @Override  
  57.             public void onClick(View v) {  
  58.                 insert(reslover, uri);  
  59.             }  
  60.         });  
  61.   
  62.         Button deleteButton = (Button) findViewById(R.id.deleteButton);  
  63.         deleteButton.setOnClickListener(new View.OnClickListener() {  
  64.             @Override  
  65.             public void onClick(View v) {  
  66.                 delete(reslover, uri);  
  67.             }  
  68.         });  
  69.           
  70.         Button updateButton = (Button) findViewById(R.id.updateButton);  
  71.         updateButton.setOnClickListener(new View.OnClickListener() {  
  72.             @Override  
  73.             public void onClick(View v) {  
  74.                 update(reslover, uri);  
  75.             }  
  76.         });  
  77.           
  78.         Button queryButton = (Button) findViewById(R.id.queryButton);  
  79.         queryButton.setOnClickListener(new View.OnClickListener() {  
  80.             @Override  
  81.             public void onClick(View v) {  
  82.                 query(reslover, uri);  
  83.             }  
  84.         });  
  85.           
  86.     }  
  87.   
  88.     private void insert(ContentResolver resolver, Uri uri) {  
  89.         ContentValues contentValues = new ContentValues();  
  90.         contentValues.put("name", "张小凡");  
  91.         contentValues.put("age", 22);  
  92.         contentValues.put("isMan", true);  
  93.         Uri uri2 = resolver.insert(uri, contentValues);  
  94.         Log.i(tag, "插入成功!");  
  95.         result += "成功插入了一条记录,uri为" + uri2;  
  96.         textView.setText(result);  
  97.         result = "";  
  98.     }  
  99.   
  100.     private void update(ContentResolver resolver, Uri uri) {  
  101.         ContentValues contentValues = new ContentValues();  
  102.         contentValues.put("age", 122);  
  103.         int number = resolver.update(uri, contentValues, null, null);  
  104.         Log.i(tag, "更新成功!");  
  105.         result += "成功更新了" + number+"条记录";  
  106.         textView.setText(result);  
  107.         result = "";  
  108.   
  109.     }  
  110.     private void delete(ContentResolver resolver, Uri uri) {  
  111.         String where = " 1=1 and isMan=?";  
  112.         //这里要注意哦,sqlite数据库中是没有boolean的,true会被转成1存储  
  113.         String[] selectionArgs = new String[] { "1" };  
  114.         int number = resolver.delete(uri, where, selectionArgs);  
  115.         Log.i(tag, "删除成功!");  
  116.         textView.setText(result + "成功删除了" + number + "条记录");  
  117.         result = "";  
  118.     }  
  119.   
  120.     private void query(ContentResolver resolver, Uri uri) {  
  121.   
  122.         String[] projection = new String[] { "id", "name", "age", "isMan" };  
  123.         Cursor cursor = resolver.query(uri, projection, null, null, null);  
  124.         int count = cursor.getCount();  
  125.         Log.i(tag, "总记录数" + count);  
  126.   
  127.         int idIndex = cursor.getColumnIndex("id");  
  128.         int nameIndex = cursor.getColumnIndex("name");  
  129.         int ageIndex = cursor.getColumnIndex("age");  
  130.         int isManIndex = cursor.getColumnIndex("isMan");  
  131.   
  132.         cursor.moveToFirst();  
  133.         while (!cursor.isAfterLast()) {  
  134.             int id = cursor.getInt(idIndex);  
  135.             String name = cursor.getString(nameIndex);  
  136.             int age = cursor.getInt(ageIndex);  
  137.             int isMan = cursor.getInt(isManIndex);  
  138.             Log.i(tag, "id=" + id + " name=" + name + " age=" + age + " isMan="  
  139.                     + isMan);  
  140.             result += "id=" + id + " name=" + name + " age=" + age + " isMan="  
  141.                     + isMan;  
  142.             cursor.moveToNext();  
  143.         }  
  144.   
  145.         textView.setText(result);  
  146.         result = "";  
  147.   
  148.     }  
  149.   
  150. }  

manifest.xml

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"  
  3.       package="cn.com.chenzheng_java"  
  4.       android:versionCode="1"  
  5.       android:versionName="1.0">  
  6.     <uses-sdk android:minSdkVersion="8" />  
  7.   
  8.     <application android:icon="@drawable/icon" android:label="@string/app_name">  
  9.         <activity android:name=".ContentAccessActivity"  
  10.                   android:label="@string/app_name">  
  11.             <intent-filter>  
  12.                 <action android:name="android.intent.action.MAIN" />  
  13.                 <category android:name="android.intent.category.LAUNCHER" />  
  14.             </intent-filter>  
  15.         </activity>  
  16.   
  17.     </application>  
  18.     <!-- 添加对内容提供者访问的权限,该权限是有我们自己定义的哦 -->  
  19.     <uses-permission android:name="cn.com.chenzheng_java.permission"></uses-permission>  
  20. </manifest>  

main.xml

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:orientation="vertical"  
  4.     android:layout_width="fill_parent"  
  5.     android:layout_height="fill_parent"  
  6.     >  
  7. <TextView    
  8.     android:id="@+id/textView"  
  9.     android:layout_width="fill_parent"   
  10.     android:layout_height="wrap_content"   
  11.     android:text="@string/hello"  
  12.     />  
  13.  <Button  
  14.     android:id="@+id/insertButton"  
  15.     android:layout_width="wrap_content"   
  16.     android:layout_height="wrap_content"   
  17.     android:text="insert"  
  18.  ></Button>  
  19.  <Button  
  20.     android:id="@+id/deleteButton"  
  21.     android:layout_width="wrap_content"   
  22.     android:layout_height="wrap_content"   
  23.     android:text="delete"  
  24.  ></Button>  
  25.  <Button  
  26.     android:id="@+id/updateButton"  
  27.     android:layout_width="wrap_content"   
  28.     android:layout_height="wrap_content"   
  29.     android:text="update"  
  30.  ></Button>  
  31.  <Button  
  32.     android:id="@+id/queryButton"  
  33.     android:layout_width="wrap_content"   
  34.     android:layout_height="wrap_content"   
  35.     android:text="query"  
  36.  ></Button>  
  37. </LinearLayout>  

--------------------------------------------------------------------------------

想说的话,在代码的注释中已经说的很清晰了。这里再次重复下我们定义和使用内容提供者的步骤吧。

定义内容提供者:

      我们定义内容提供者的目的是什么,共享数据,对,定义内容提供者的目的就是让别的应用能够访问当前应用的一些数据,至于到底暴露给外界什么数据,我们可以 在定义内容提供者的时候详细控制!不管如何,我们明确了第一个问题,定义内容提供者的目的----数据共享!

      我们平时对数据的操作都有哪些?增删改查!就四个字!这也是为什么我们再定义内容提供者的时候必须要实现相应的方法了。当然如果你要是不想提供相应的操作,你可以在内部进行方法空实现。

     是不是所有的应用都可以访问我啊?不可能!我们可不是随便的人,对吧!所以我们要进行验证,验证不通过的直接让它去死就可以了。验证怎么验证啊?通过UriMatcher进行匹配!

     现在我们已经提供了访问接口了,我们怎么让系统知道,别的应用可以用我的东西啊?去配置文件中注册!!

使用内容提供者:

      如何找到该内容提供者啊?需要Uri和相应的访问权限。相当于地址

      如何进行增删查改啊?通过ContentResolver对象的相应方法。

原文地址:https://www.cnblogs.com/xgjblog/p/3922059.html