android ContentProvider

来源:互联网 发布:tp路由器访客网络设置 编辑:程序博客网 时间:2024/05/22 00:18
 Content Provider 属于Android应用程序的组件之一,作为应用程序之间唯一的共享数据的途径,Content Provider 主要的功能就是存储并检索数据以及向其他应用程序提供访问数据的借口。

    Android 系统为一些常见的数据类型(如音乐、视频、图像、手机通信录联系人信息等)内置了一系列的 Content Provider, 这些都位于android.provider包下。持有特定的许可,可以在自己开发的应用程序中访问这些Content Provider。

   让自己的数据和其他应用程序共享有两种方式:创建自己的Content Provier(即继承自ContentProvider的子类)  或者是将自己的数据添加到已有的Content Provider中去,后者需要保证现有的Content Provider和自己的数据类型相同且具有该 Content Provider的写入权限。对于Content Provider,最重要的就是数据模型(data model) 和 URI。

   1.数据模型 
    Content Provider 将其存储的数据以数据表的形式提供给访问者,在数据表中每一行为一条记录,每一列为具有特定类型和意义的数据。每一条数据记录都包括一个 "_ID" 数值字段,改字段唯一标识一条数据。

     2.URI 
     URI,每一个Content Provider 都对外提供一个能够唯一标识自己数据集(data set)的公开URI, 如果一个Content Provider管理多个数据集,其将会为每个数据集分配一个独立的URI。所有的Content Provider 的URI 都以"content://" 开头,其中"content:"是用来标识数据是由Content Provider管理的 schema。 

     下面通过继承Content Provier来写一个实例。

     首先建立一个sqlite实例,具体细节见上一节sqlite实例,这里就只给出代码:

     第一步建立一个ContentProviderDemo:

      

     第二步建立DBOpenHelper类:

      

[java] view plain copy
  1. public class DBOpenHelper extends SQLiteOpenHelper {  
  2.       
  3.     private static final String DATABASE_NAME = "person.db"//数据库名称  
  4.     private static final int DATABASE_VERSION = 1;//数据库版本  
  5.       
  6.     public DBOpenHelper(Context context) {  
  7.         super(context, DATABASE_NAME, null, DATABASE_VERSION);  
  8.         // TODO Auto-generated constructor stub  
  9.     }  
  10.   
  11.     @Override  
  12.     public void onCreate(SQLiteDatabase db) {  
  13.             
  14.         db.execSQL("CREATE TABLE person (_id integer primary key autoincrement, name varchar(20), age varchar(10))");  
  15.     }  
  16.   
  17.     @Override  
  18.     public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {  
  19.         // TODO Auto-generated method stub  
  20.         db.execSQL("DROP TABLE IF EXISTS person");  
  21.         onCreate(db);  
  22.     }  
  23.   
  24. }  
        在上面创建了一个person表,

    

[java] view plain copy
  1. public class PersonService {  
  2.   
  3.       private DBOpenHelper dbOpenHelper;  
  4.         
  5.       public PersonService(Context context) {  
  6.         // TODO Auto-generated constructor stub  
  7.           dbOpenHelper=new DBOpenHelper(context);  
  8.     }  
  9.       public void save(Person person){  
  10.           SQLiteDatabase db=dbOpenHelper.getWritableDatabase();  
  11.           db.execSQL("insert into person(name,age) values(?,?)",new Object[]{person.getName(),person.getAge()});  
  12.       }  
  13.       public void delete(Integer _id){  
  14.           SQLiteDatabase db=dbOpenHelper.getWritableDatabase();  
  15.           db.execSQL("delete from person where _id=?",new Object[]{_id});  
  16.       }  
  17.       public Person find(Integer _id){  
  18.           SQLiteDatabase db=dbOpenHelper.getReadableDatabase();  
  19.           Cursor cursor=db.rawQuery("select * from person where _id=?"new String[]{_id.toString()});  
  20.           if(cursor.moveToFirst()){  
  21.                 int id = cursor.getInt(cursor.getColumnIndex("_id"));  
  22.                 String name = cursor.getString(cursor.getColumnIndex("name"));  
  23.                 String age = cursor.getString(cursor.getColumnIndex("age"));  
  24.                 Person person = new Person();  
  25.                 person.set_id(id);  
  26.                 person.setName(name);  
  27.                 person.setAge(age);  
  28.                 return person;  
  29.           }  
  30.           return null;  
  31.       }  
  32.       public List<Person> findAll(){  
  33.           SQLiteDatabase db=dbOpenHelper.getReadableDatabase();  
  34.           List<Person> persons = new ArrayList<Person>();  
  35.           Cursor cursor=db.rawQuery("select * from person"null);  
  36.           while(cursor.moveToNext()){  
  37.               Person person=new Person();  
  38.             int id=cursor.getInt(cursor.getColumnIndex("_id"));  
  39.             String name=cursor.getString(cursor.getColumnIndex("name"));  
  40.             String age=cursor.getString(cursor.getColumnIndex("age"));  
  41.             person.set_id(id);  
  42.             person.setName(name);  
  43.             person.setAge(age);  
  44.             persons.add(person);  
  45.           }  
  46.           return persons;  
  47.       }  
  48. }  
        实现person的增删改查,

     

[java] view plain copy
  1. public class Person {  
  2.   
  3.     private Integer _id;  
  4.     private String name;  
  5.     private String age;  
  6.       
  7.     public Integer get_id() {  
  8.         return _id;  
  9.     }  
  10.     public void set_id(Integer _id) {  
  11.         this._id = _id;  
  12.     }  
  13.     public String getName() {  
  14.         return name;  
  15.     }  
  16.     public void setName(String name) {  
  17.         this.name = name;  
  18.     }  
  19.     public String getAge() {  
  20.         return age;  
  21.     }  
  22.     public void setAge(String age) {  
  23.         this.age = age;  
  24.     }  
  25.       
  26. }  
      OK!数据库已建好,接下来就是要实现ContentProvider来提供统一的访问接口:

    

[java] view plain copy
  1. public class PersonProvider extends ContentProvider {  
  2.     private DBOpenHelper dbOpenHelper;  
  3.     private static final UriMatcher MATCHER = new UriMatcher(  
  4.             UriMatcher.NO_MATCH);  
  5.     private static final int PERSONS = 1;  
  6.     private static final int PERSON = 2;  
  7.     static {  
  8.         MATCHER.addURI("cn.com.karl.personProvider""person", PERSONS);  
  9.         MATCHER.addURI("cn.com.karl.personProvider""person/#", PERSON);  
  10.     }  
  11.   
  12.     @Override  
  13.     public boolean onCreate() {  
  14.         // TODO Auto-generated method stub  
  15.         this.dbOpenHelper = new DBOpenHelper(this.getContext());  
  16.         return false;  
  17.     }  
  18.   
  19.     @Override  
  20.     public Cursor query(Uri uri, String[] projection, String selection,  
  21.             String[] selectionArgs, String sortOrder) {  
  22.         // TODO Auto-generated method stub  
  23.         SQLiteDatabase db = dbOpenHelper.getReadableDatabase();  
  24.         switch (MATCHER.match(uri)) {  
  25.         case PERSONS:  
  26.             return db.query("person", projection, selection, selectionArgs,  
  27.                     nullnull, sortOrder);  
  28.   
  29.         case PERSON:  
  30.             long id = ContentUris.parseId(uri);  
  31.             String where = "_id=" + id;  
  32.             if (selection != null && !"".equals(selection)) {  
  33.                 where = selection + " and " + where;  
  34.             }  
  35.             return db.query("person", projection, where, selectionArgs, null,  
  36.                     null, sortOrder);  
  37.   
  38.         default:  
  39.             throw new IllegalArgumentException("Unkwon Uri:" + uri.toString());  
  40.         }  
  41.     }  
  42.       
  43.     //返回数据的MIME类型。  
  44.     @Override  
  45.     public String getType(Uri uri) {  
  46.         // TODO Auto-generated method stub  
  47.         switch (MATCHER.match(uri)) {  
  48.         case PERSONS:  
  49.             return "vnd.android.cursor.dir/person";  
  50.   
  51.         case PERSON:  
  52.             return "vnd.android.cursor.item/person";  
  53.   
  54.         default:  
  55.             throw new IllegalArgumentException("Unkwon Uri:" + uri.toString());  
  56.         }  
  57.     }  
  58.   
  59.     // 插入person表中的所有记录 /person  
  60.     // 插入person表中指定id的记录 /person/10  
  61.     @Override  
  62.     public Uri insert(Uri uri, ContentValues values) {  
  63.         // TODO Auto-generated method stub  
  64.         SQLiteDatabase db = dbOpenHelper.getWritableDatabase();  
  65.         switch (MATCHER.match(uri)) {  
  66.         case PERSONS:  
  67.             // 特别说一下第二个参数是当name字段为空时,将自动插入一个NULL。  
  68.             long rowid = db.insert("person""name", values);  
  69.             Uri insertUri = ContentUris.withAppendedId(uri, rowid);// 得到代表新增记录的Uri  
  70.             this.getContext().getContentResolver().notifyChange(uri, null);  
  71.             return insertUri;  
  72.   
  73.         default:  
  74.             throw new IllegalArgumentException("Unkwon Uri:" + uri.toString());  
  75.         }  
  76.     }  
  77.   
  78.     @Override  
  79.     public int delete(Uri uri, String selection, String[] selectionArgs) {  
  80.         // TODO Auto-generated method stub  
  81.         SQLiteDatabase db = dbOpenHelper.getWritableDatabase();  
  82.         int count = 0;  
  83.         switch (MATCHER.match(uri)) {  
  84.         case PERSONS:  
  85.             count = db.delete("person", selection, selectionArgs);  
  86.             return count;  
  87.   
  88.         case PERSON:  
  89.             long id = ContentUris.parseId(uri);  
  90.             String where = "_id=" + id;  
  91.             if (selection != null && !"".equals(selection)) {  
  92.                 where = selection + " and " + where;  
  93.             }  
  94.             count = db.delete("person", where, selectionArgs);  
  95.             return count;  
  96.   
  97.         default:  
  98.             throw new IllegalArgumentException("Unkwon Uri:" + uri.toString());  
  99.         }  
  100.     }  
  101.   
  102.     @Override  
  103.     public int update(Uri uri, ContentValues values, String selection,  
  104.             String[] selectionArgs) {  
  105.         // TODO Auto-generated method stub  
  106.         SQLiteDatabase db = dbOpenHelper.getWritableDatabase();  
  107.         int count = 0;  
  108.         switch (MATCHER.match(uri)) {  
  109.         case PERSONS:  
  110.             count = db.update("person", values, selection, selectionArgs);  
  111.             return count;  
  112.         case PERSON:  
  113.             long id = ContentUris.parseId(uri);  
  114.             String where = "_id=" + id;  
  115.             if (selection != null && !"".equals(selection)) {  
  116.                 where = selection + " and " + where;  
  117.             }  
  118.             count = db.update("person", values, where, selectionArgs);  
  119.             return count;  
  120.         default:  
  121.             throw new IllegalArgumentException("Unkwon Uri:" + uri.toString());  
  122.         }  
  123.     }  
  124.   
  125. }  
             最后不要忘记在manifest里注册
    
[html] view plain copy
  1. <provider android:name=".PersonProvider"   
  2.         android:authorities="cn.com.karl.personProvider"/>  
            这样基本上就已经完成,让我们再写个项目访问一下,建立ResolverDemo项目:

            

           为了展现效果,我们用了ListView,在res下建立item.xml

     

[html] view plain copy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout  
  3.   xmlns:android="http://schemas.android.com/apk/res/android"  
  4.   android:orientation="horizontal"  
  5.   android:layout_width="fill_parent"  
  6.   android:layout_height="wrap_content">  
  7.    
  8.      <TextView  
  9.           android:layout_width="80dip"  
  10.           android:layout_height="wrap_content"  
  11.           android:text="435"  
  12.           android:id="@+id/id"  
  13.           />  
  14.         
  15.      <TextView  
  16.           android:layout_width="100dip"  
  17.           android:layout_height="wrap_content"  
  18.            android:text="liming"  
  19.           android:id="@+id/name"  
  20.           />     
  21.             
  22.      <TextView  
  23.           android:layout_width="fill_parent"  
  24.           android:layout_height="wrap_content"  
  25.            android:text="45"  
  26.           android:id="@+id/age"  
  27.           />     
  28.         
  29. </LinearLayout>  
        
    
[java] view plain copy
  1. public class ResolverDemoActivity extends Activity {  
  2.     /** Called when the activity is first created. */  
  3.     private   SimpleCursorAdapter adapter;  
  4.     private ListView listView;  
  5.     @Override  
  6.     public void onCreate(Bundle savedInstanceState) {  
  7.         super.onCreate(savedInstanceState);  
  8.         setContentView(R.layout.main);  
  9.           
  10.          listView=(ListView) this.findViewById(R.id.listView);  
  11.         ContentResolver contentResolver = getContentResolver();  
  12.         Uri selectUri = Uri.parse("content://cn.com.karl.personProvider/person");  
  13.         Cursor cursor=contentResolver.query(selectUri, nullnullnullnull);  
  14.          adapter = new SimpleCursorAdapter(this, R.layout.item, cursor,  
  15.                     new String[]{"_id""name""age"}, new int[]{R.id.id, R.id.name, R.id.age});  
  16.             listView.setAdapter(adapter);  
  17.             listView.setOnItemClickListener(new OnItemClickListener() {  
  18.                 @Override  
  19.                 public void onItemClick(AdapterView<?> parent, View view, int position, long id) {  
  20.                     ListView lView = (ListView)parent;  
  21.                     Cursor data = (Cursor)lView.getItemAtPosition(position);  
  22.                     int _id = data.getInt(data.getColumnIndex("_id"));  
  23.                     Toast.makeText(ResolverDemoActivity.this, _id+""1).show();  
  24.                 }  
  25.             });  
  26.               
  27.             Button button = (Button) this.findViewById(R.id.insertbutton);  
  28.             button.setOnClickListener(new View.OnClickListener() {            
  29.                 @Override  
  30.                 public void onClick(View v) {  
  31.                     ContentResolver contentResolver = getContentResolver();  
  32.                     Uri insertUri = Uri.parse("content://cn.com.karl.personProvider/person");  
  33.                     ContentValues values = new ContentValues();  
  34.                     values.put("name""wangkuifeng");  
  35.                     values.put("age"23);  
  36.                     Uri uri = contentResolver.insert(insertUri, values);  
  37.                     Toast.makeText(ResolverDemoActivity.this"添加完成"1).show();  
  38.                 }  
  39.             });  
  40.     }  
  41. }  
      用ContentResolver来访问,其实在使用Content Provider得到联系人信息这一节就已经用过这个类了,只是那一节是访问系统提供的ContentProvider,这一节是我们自己实现的ContentProvider。

         

       最后让我们看一下运行效果吧!

       

原创粉丝点击