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;
}
}
}
}

猜你喜欢

转载自blog.csdn.net/guizhaiteng/article/details/50973743
今日推荐