Content Provider應用實例

http://blog.csdn.net/wangkuifeng0118/article/details/7028953


包含了content Provider應用實例   和  sqlite 創建和基本使用


  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。

         

       最後讓我們看一下運行效果吧!

       

       


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章