1. 程式人生 > >Android初試--Android中的ContentProvider(2)

Android初試--Android中的ContentProvider(2)

ContentProvider(內容提供者、資料共享)
建立ContentProvider
   1.建立一個新類繼承ContentProvider
   2.重寫必要的方法
        public boolean onCreate();
該方法在ContentProvider建立後就會被呼叫,Android開機後,ContentProvider在其它應用第一次訪問它時才會被建立。
public Uri insert(Uri uri, ContentValues values);
該方法用於供外部應用往ContentProvider新增資料。
public int delete(Uri uri, String selection, String[] selectionArgs);
該方法用於供外部應用從ContentProvider刪除資料。
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs);
該方法用於供外部應用更新ContentProvider中的資料。
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder);
該方法用於供外部應用從ContentProvider中獲取資料。
public String getType(Uri uri);
該方法返回當前Uri所代表資料的MIME型別。
        如果要操作的資料屬於集合型別,那麼MIME型別字串應該以vnd.android.cursor.dir/開頭
        如果要操作的資料屬於非集合型別資料,那麼MIME型別字串應該以vnd.android.cursor.item/開頭
   3.配置
<manifest .... >
    <application android:icon="@drawable/icon" android:label="@string/app_name">
...................
        <provider android:name=".PersonContentProvider" android:authorities="com.rxr.providers.personprovider"/>
    </application>
</manifest>
     android:authorities="com.rxr.providers.personprovider"  的訪問方式
Uri-----訪問ContentProvider的路徑
Uri代表了要操作的資料,主要包含兩部分資訊:
1、需要操作的ContentProvider。
2、對ContentProvider中的什麼資料進行操作。
一個Uri由以下幾部分組成:
content://com.rxr.providers.personprovider/person/1
|————|————————————————|—————|
  schema       主機名或域名                   路徑
schema----schema為content://
主機名或域名-------需要操作的ContentProvider  
路徑-------操作 ContentProvider中的資料。      
Uri----訪問person表
   content://com.rxr.providers.personprovider/person
Uri----訪問person表第2條資料
   content://com.rxr.providers.personprovider/person/2
Uri----訪問person表第2條資料name值
   content://com.rxr.providers.personprovider/person/2/age
Uri類中的parse()方法---將字串轉化成Uri物件。
UriMatcher類---匹配的Uri路徑
   addURI(“Uri路徑”,"表名稱",返回匹配碼)
   match(uri)方法對輸入的Uri進行匹配,如果匹配就返回匹配碼。
ContentUris類使用介紹
ContentUris類用於操作Uri路徑後面的ID部分,它有兩個比較實用的方法
   withAppendedId(uri, id)用於為路徑加上ID部分
   parseId(uri)方法用於從路徑中獲取ID部分:
ContentResolver類
當外部應用需要對ContentProvider中的資料進行新增、刪除、修改和查詢操作
監聽ContentProvider中資料的變化
ContentProvider的訪問者需要知道ContentProvider中的資料是否發生了變化,則發生資料變化時在ContentProvider中呼叫getContentResolver().notifyChange(Uri uri, ContentObserver observer)方法通知註冊在此Uri上的訪問者。

DBOpenHelper.java

package com.example.contentproviderdemo;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DBOpenHelper extends SQLiteOpenHelper{
    private  static final String  databasename="data_db"; 
    private  static final int  databaseversion=1; 
public DBOpenHelper(Context context) {
super(context, databasename, null, databaseversion);
}
@Override
public void onCreate(SQLiteDatabase database) {
database.execSQL("create table person(personid integer primary key autoincrement, name varchar(20), age integer)");
}
@Override
public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {
}
}

PersonContentProvider.java

package com.example.contentproviderdemo;
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;
public class PersonContentProvider extends ContentProvider{
private  DBOpenHelper  dbOpenHelper=null;
//常量UriMatcher.NO_MATCH表示不匹配任何路徑時的返回碼
private static final UriMatcher URI_MATCHER = new UriMatcher(UriMatcher.NO_MATCH);
////新增需要匹配的uri,如果匹配就會返回匹配碼
static{
// content://com.rxr.test.personcontentprovider/person
URI_MATCHER.addURI("com.rxr.test.personcontentprovider", "person", 1);
// content://com.rxr.test.personcontentprovider/person/2
// content://com.rxr.test.personcontentprovider/person/2/name
URI_MATCHER.addURI("com.rxr.test.personcontentprovider", "person/#", 2);
}
@Override
public boolean onCreate() {
this.dbOpenHelper=new DBOpenHelper(getContext());
return true;
}
@Override
public String getType(Uri uri) {
String  info=null;
switch(URI_MATCHER.match(uri)){
case 1:
info="vnd.android.cursor.dir/person";  //集合資料
break;
case 2:
info="vnd.android.cursor.item/person"; //非集合型別
break;
   default:throw new IllegalArgumentException("不知道的uri:" + uri);
}
return info;
}
public Uri insert(Uri uri, ContentValues values) {
//得到sqliteDatabase物件
SQLiteDatabase  database=dbOpenHelper.getWritableDatabase();
switch(URI_MATCHER.match(uri)){
case 1:
long  rowid =database.insert("person", null, values);
Uri insertUri= ContentUris.withAppendedId(uri, rowid);
this.getContext().getContentResolver().notifyChange(uri, null);
return insertUri;
default :throw new IllegalArgumentException("不知道的uri:" + uri);
}
}
@Override
public int delete(Uri uri, String selection, String[] selectionargs) {
//得到sqliteDatabase物件
SQLiteDatabase  database=dbOpenHelper.getWritableDatabase();
int count = 0;
   switch(URI_MATCHER.match(uri)){
//content://com.rxr.test.personcontentprovider/person
   case 1://刪除整張表中的資料
    count=database.delete("person", selection, selectionargs);
       return count;
   case 2://刪除整張表中的某一條資料
    //content://com.rxr.test.personcontentprovider/person/2
    long id = ContentUris.parseId(uri);
    //根據id刪除資料
    String whereString = "personid=" + id;
    if(selection != null && !"".equals(selection)){
whereString = selection + " and " + whereString;
}
    count=database.delete("person", whereString, selectionargs);
       return count;    
   default:
throw new IllegalArgumentException("不知道的uri:" + uri);
}
}
@Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionargs) {
//得到sqliteDatabase物件
SQLiteDatabase  database=dbOpenHelper.getWritableDatabase();
int count = 0;
switch(URI_MATCHER.match(uri)){
//content://com.rxr.test.personcontentprovider/person
   case 1://修改整張表中的資料
    count=database.update("person", values, selection, selectionargs);
       return count;
   case 2://修改整張表中的某一條資料
    //content://com.rxr.test.personcontentprovider/person/2
    long id = ContentUris.parseId(uri);
    //根據id修改資料
    String whereString = "personid=" + id;
    if(selection != null && !"".equals(selection)){
whereString = selection + " and " + whereString;
}
    count=database.update("person",values, whereString, selectionargs);
       return count;    
   default:
throw new IllegalArgumentException("不知道的uri:" + uri);
}
}
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionargs,String sortOrder) {
//得到sqliteDatabase物件
SQLiteDatabase  database=dbOpenHelper.getWritableDatabase();
Cursor cursor =null;
switch(URI_MATCHER.match(uri)){
//content://com.rxr.test.personcontentprovider/person
   case 1://查詢整張表中的資料
    cursor=database.query("person", projection, selection, selectionargs, null, null, sortOrder);
       return cursor;
   case 2://查詢整張表中的某一條資料
    //content://com.rxr.test.personcontentprovider/person/2
    long id = ContentUris.parseId(uri);
    //根據id修改資料
    String whereString = "personid=" + id;
    if(selection != null && !"".equals(selection)){
whereString = selection + " and " + whereString;
}
    cursor=database.query("person", projection, whereString, selectionargs, null, null, sortOrder);
       return cursor;    
   default:
throw new IllegalArgumentException("不知道的uri:" + uri);
}

}

main佈局


<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:id="@+id/button1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="向ContentProvider新增資料" />
    <Button
        android:id="@+id/button2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="修改ContentProvider中的資料" />
    <Button
        android:id="@+id/button3"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="查詢ContentProvider中所有資料" />
    <Button
        android:id="@+id/button4"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="查詢ContentProvider中某一條資料" />
    <Button
        android:id="@+id/button5"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="刪除ContentProvider中某一條資料" />
    <Button
        android:id="@+id/button6"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="得到ContentProvider的URI的資料型別" />
</LinearLayout>

MainActivity.java

package com.example.contentproviderdemo;
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.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity {
   private  MyClick  click=null;
   private  Button insertButton=null;
   private  Button updateButton=null;
   private  Button selectAllButton=null;
   private  Button selectAButton=null;
   private  Button deleteButton=null;
   private  Button typeButton=null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
}
private void initView() {
click=new MyClick();
insertButton=(Button)findViewById(R.id.button1);
insertButton.setOnClickListener(click);
updateButton=(Button)findViewById(R.id.button2);
updateButton.setOnClickListener(click);
selectAllButton=(Button)findViewById(R.id.button3);
selectAllButton.setOnClickListener(click);
selectAButton=(Button)findViewById(R.id.button4);
selectAButton.setOnClickListener(click);
deleteButton=(Button)findViewById(R.id.button5);
deleteButton.setOnClickListener(click);
typeButton=(Button)findViewById(R.id.button6);
typeButton.setOnClickListener(click);
}
public  class  MyClick  implements OnClickListener{
@Override
public void onClick(View view) {
ContentResolver contentResolver=MainActivity.this.getContentResolver();  
switch(view.getId()){
case  R.id.button1:
String insertString="content://com.rxr.test.personcontentprovider/person";
Uri inserturi=Uri.parse(insertString);
ContentValues  values=new ContentValues();
values.put("name", "wangwu");
values.put("age", 23);
Uri newUri=contentResolver.insert(inserturi, values);
System.out.println(newUri.toString());
   break;
case  R.id.button2:
String updateString="content://com.rxr.test.personcontentprovider/person/1";
Uri updateuri=Uri.parse(updateString);
ContentValues  updatevalues=new ContentValues();
updatevalues.put("name", "lisi");
updatevalues.put("age", 34);
int  temp=contentResolver.update(updateuri, updatevalues, null, null);
System.out.println(temp);
break;
case  R.id.button3:
String selectString="content://com.rxr.test.personcontentprovider/person";
Uri selecturi=Uri.parse(selectString);
Cursor cursor=contentResolver.query(selecturi, null, null, null, null);
while(cursor.moveToNext()){
int  id=cursor.getInt(cursor.getColumnIndex("personid"));
String name=cursor.getString(cursor.getColumnIndex("name"));
int  age=cursor.getInt(cursor.getColumnIndex("age"));
System.out.println(id+"   "+name+"   "+age);
}
cursor.close();
break;
case  R.id.button4:
String selectaString="content://com.rxr.test.personcontentprovider/person/2";
Uri selectauri=Uri.parse(selectaString);
Cursor cursor2=contentResolver.query(selectauri, null, null, null, null);
while(cursor2.moveToNext()){
int  id=cursor2.getInt(cursor2.getColumnIndex("personid"));
String name=cursor2.getString(cursor2.getColumnIndex("name"));
int  age=cursor2.getInt(cursor2.getColumnIndex("age"));
System.out.println(id+"   "+name+"   "+age);
}
cursor2.close();
break;
case  R.id.button5:
String deleteString="content://com.rxr.test.personcontentprovider/person/2";
Uri deleteuri=Uri.parse(deleteString);
int temp2=contentResolver.delete(deleteuri, null, null);
System.out.println(temp2);
break;
case  R.id.button6:
String typeString="content://com.rxr.test.personcontentprovider/person";
Uri   typeuri=Uri.parse(typeString);
String  typeinfo=contentResolver.getType(typeuri);
System.out.println(typeinfo);
break;
}
}
}
}