Android开发13——内容提供者ContentProvider的基本使用

一、ContentProvider简介

当应用继承ContentProvider类,并重写该类用于提供数据和存储数据的方法,就可以向其他应用共享其数据。ContentProvider为存储和获取数据提供了统一的接口。虽然使用其他方法也可以对外共享数据,但数据访问方式会因数据存储的方式而不同,如采用文件方式对外共享数据,需要进行文件操作读写数据;采用sharedpreferences共享数据,需要使用sharedpreferences API读写数据。而使用ContentProvider共享数据的好处是统一了数据访问方式。

 

query(Uri uri, String[] projection, String selection, String[] selectionArgs,String sortOrder)
通过Uri进行查询,返回一个Cursor

insert(Uri url, ContentValues values)
将一组数据插入到Uri 指定的地方

update(Uri uri, ContentValues values, String where, String[] selectionArgs)
更新Uri指定位置的数据

delete(Uri url, String where, String[] selectionArgs)
删除指定Uri并且符合一定条件的数据

 

 

二、Uri类简介

Uri代表了要操作的数据,Uri主要包含了两部分信息
①需要操作的ContentProvider
②对ContentProvider中的什么数据进行操作

 

组成部分
scheme:ContentProvider的scheme已经由Android所规定为content://
主机名(Authority):用于唯一标识这个ContentProvider,外部调用者可以根据这个标识来找到它。建议为公司域名,保持唯一性
③路径(path):可以用来表示我们要操作的数据,路径的构建应根据业务而定:

 

要操作person表中id为10的记录
content://cn.xyCompany.providers.personProvider/person/10

 

要操作person表中id为10的记录的name字段
content://cn.xyCompany.providers.personProvider/person/10/name

 

要操作person表中的所有记录
content://cn.xyCompany.providers.personProvider/person

 

要操作的数据不一定来自数据库,也可以是文件等他存储方式,如要操作xml文件中user节点下的name节点

content://cn.xyCompany.providers.personProvider/person/10/name

 

把一个字符串转换成Uri,可以使用Uri类中的parse()方法
Uri uri = Uri.parse("content://cn.xyCompany.providers.personProvider/person")

 

三、UriMatcher、ContentUris和ContentResolver简介

Uri代表了要操作的数据,所以经常需要解析Uri,并从Uri中获取数据。Android系统提供了两个用于操作Uri的工具类,分别为UriMatcher 和ContentUris。掌握它们的使用会便于我们的开发工作。

 

UriMatcher

用于匹配Uri

①把需要匹配Uri路径全部给注册上

// 常量UriMatcher.NO_MATCH表示不匹配任何路径的返回码(-1)。
UriMatcher  uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);

// 若match()方法匹配content://cn.xyCompany.providers.personProvider/person路径则返回匹配码为1
uriMatcher.addURI("content://cn.xyCompany.providers.personProvider","person", 1);

// 若match()方法匹配content://cn.xyCompany.providers.personProvider/person/10路径则返回匹配码为2
uriMatcher.addURI("content://cn.xyCompany.providers.personProvider","person/#", 1);

②注册完需要匹配的Uri后,就可以使用uriMatcher.match(uri)方法对输入的Uri进行匹配


ContentUris
ContentUris是对URI的操作类,其中的withAppendedId(uri, id)用于为路径加上ID部分,parseId(uri)方法用于从路径中获取ID部分方法很实用。
Uri insertUri = Uri.parse("content://cn.xyCompany.providers.personProvider/person" + id);等价于
Uri insertUri = ContentUris.withAppendedId(uri, id);


ContentResolver
当外部应用需要对ContentProvider中的数据进行添加、删除、修改和查询操作时,可以使用ContentResolver 类来完成。要获取ContentResolver 对
象,可以使用Activity提供的getContentResolver()方法。 ContentResolver使用insert、delete、update、query方法来操作数据。

 

三、实例代码

当数据需要在应用程序间共享时,我们就可以利用ContentProvider为数据定义一个URI。之后其他应用程序对数据进行查询或者修改时,只需要从当前上下文对象获得一个ContentResolver(内容解析器)传入相应的URI就可以了。

contentProvider和Activity一样是Android的组件,故使用前需要在AndroidManifest.xml中注册,必须放在主应用所在包或其子包下。

    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".MainActivity"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
            <intent-filter>
                <data android:mimeType="vnd.android.cursor.dir/person" />
            </intent-filter>
            <intent-filter>
                <data android:mimeType="vnd.android.cursor.item/person" />
            </intent-filter>
        </activity>
        <!-- 配置内容提供者,android:authorities为该内容提供者取名作为在本应用中的唯一标识 -->
        <provider android:name=".providers.PersonProvider"
                android:authorities="cn.xyCompany.providers.personProvider"/>
    </application>

 

内容提供者和测试代码 

内容提供者
package cn.xy.cotentProvider.app.providers;
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;
import android.util.Log;
import cn.xy.cotentProvider.service.DBOpeningHelper;


public class PersonProvider extends ContentProvider
{
 private DBOpeningHelper dbHelper;

 // 若不匹配采用UriMatcher.NO_MATCH(-1)返回
 private static final UriMatcher MATCHER = new UriMatcher(UriMatcher.NO_MATCH);

 // 匹配码
 private static final int CODE_NOPARAM = 1;
 private static final int CODE_PARAM = 2;

 static
 {
  // 对等待匹配的URI进行匹配操作,必须符合cn.xyCompany.providers.personProvider/person格式
  // 匹配返回CODE_NOPARAM,不匹配返回-1
  MATCHER.addURI("cn.xyCompany.providers.personProvider", "person", CODE_NOPARAM);

  // #表示数字 cn.xyCompany.providers.personProvider/person/10
  // 匹配返回CODE_PARAM,不匹配返回-1
  MATCHER.addURI("cn.xyCompany.providers.personProvider", "person/#", CODE_PARAM);
 }

 @Override
 public boolean onCreate()
 {
  dbHelper = new DBOpeningHelper(this.getContext());
  return true;
 }

 
 @Override
 public Uri insert(Uri uri, ContentValues values)
 {
  SQLiteDatabase db = dbHelper.getWritableDatabase();
  switch (MATCHER.match(uri))
  {
   case CODE_NOPARAM:
    // 若主键值是自增长的id值则返回值为主键值,否则为行号,但行号并不是RecNo列
    long id = db.insert("person", "name", values);
    Uri insertUri = ContentUris.withAppendedId(uri, id);
    return insertUri;
   default:
    throw new IllegalArgumentException("this is unkown uri:" + uri);
  }
 }

 
 @Override
 public int delete(Uri uri, String selection, String[] selectionArgs)
 {
  SQLiteDatabase db = dbHelper.getWritableDatabase();
  switch (MATCHER.match(uri))
  {
   case CODE_NOPARAM:
    return db.delete("person", selection, selectionArgs); // 删除所有记录
   case CODE_PARAM:
    long id = ContentUris.parseId(uri); // 取得跟在URI后面的数字
    Log.i("provider", String.valueOf(id));
    String where = "id = " + id;
    if (null != selection && !"".equals(selection.trim()))
    {
     where += " and " + selection;
    }
    return db.delete("person", where, selectionArgs);
   default:
    throw new IllegalArgumentException("this is unkown uri:" + uri);
  }
 }

 
 @Override
 public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs)
 {
  SQLiteDatabase db = dbHelper.getWritableDatabase();
  switch (MATCHER.match(uri))
  {
   case CODE_NOPARAM:
    return db.update("person",values,selection, selectionArgs); // 更新所有记录
   case CODE_PARAM:
    long id = ContentUris.parseId(uri); // 取得跟在URI后面的数字
    String where = "id = " + id;
    if (null != selection && !"".equals(selection.trim()))
    {
     where += " and " + selection;
    }
    return db.update("person",values,where,selectionArgs);
   default:
    throw new IllegalArgumentException("this is unkown uri:" + uri);
  }
 }
 
 
 @Override
 public String getType(Uri uri)
 {
  switch(MATCHER.match(uri))
  {
   case CODE_NOPARAM:
    return "vnd.android.cursor.dir/person";
   case CODE_PARAM:
    return "vnd.android.cursor.item/person";
   default:
    throw new IllegalArgumentException("this is unkown uri:" + uri);
  }
 }

 @Override
 public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder)
 {
  SQLiteDatabase db = dbHelper.getReadableDatabase();
  switch (MATCHER.match(uri))
  {
   case CODE_NOPARAM:
    return db.query("person", projection, selection, selectionArgs, null, null, sortOrder);
   case CODE_PARAM:
    long id = ContentUris.parseId(uri); // 取得跟在URI后面的数字
    String where = "id = " + id;
    if (null != selection && !"".equals(selection.trim()))
    {
     where += " and " + selection;
    }
    return db.query("person", projection, where, selectionArgs, null, null, sortOrder);
   default:
    throw new IllegalArgumentException("this is unkown uri:" + uri);
  }
 }

}

 

测试代码
package cn.xy.test.test;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.test.AndroidTestCase;
import android.util.Log;


public class TestProviders extends AndroidTestCase
{
 // 在执行该测试方法时需要先将还有内容提供者的项目部署到Android中,否则无法找到内容提供者
 public void testInsert()
 {
  Uri uri = Uri.parse("content://cn.xyCompany.providers.personProvider/person");
  ContentResolver resolver = this.getContext().getContentResolver();
  ContentValues values = new ContentValues();
  values.put("name", "xy");
  values.put("phone", "111");
  resolver.insert(uri, values); // 内部调用内容提供者的insert方法
 }

 // 不带id参数的删除
 public void testDelete1()
 {
  Uri uri = Uri.parse("content://cn.xyCompany.providers.personProvider/person");
  ContentResolver resolver = this.getContext().getContentResolver();
  int rowAffect = resolver.delete(uri, null, null);
  Log.i("rowAffect", String.valueOf(rowAffect));
 }

 // 带参数的删除,通过URI传递了id至contentProvider并可追加其他条件
 public void testDelete2()
 {
  Uri uri = Uri.parse("content://cn.xyCompany.providers.personProvider/person/18");
  ContentResolver resolver = this.getContext().getContentResolver();
  int rowAffect = resolver.delete(uri, "name = ?", new String[] { "XY2" }); // 在provider中手动进行了拼装
  Log.i("rowAffect", String.valueOf(rowAffect));
 }
 
 public void testUpdate()
 {
  Uri uri = Uri.parse("content://cn.xyCompany.providers.personProvider/person/19");
  ContentResolver resolver = this.getContext().getContentResolver();
  ContentValues values = new ContentValues();
  values.put("name", "newxy");
  values.put("phone", "new111");
  int rowAffect = resolver.update(uri, values, null, null);
  Log.i("rowAffect", String.valueOf(rowAffect));
 }
 
 public void testQuery()
 {
  Uri uri = Uri.parse("content://cn.xyCompany.providers.personProvider/person/19");
  ContentResolver resolver = this.getContext().getContentResolver();
  Cursor cursor = resolver.query(uri, new String[]{"id","name","phone"}, null, null, "id asc");
  if(cursor.moveToFirst())
  {
   Log.i("query", cursor.getString(cursor.getColumnIndex("name")));
  }
  cursor.close();
 }
}

参考博客:http://www.cnblogs.com/chenglong/articles/1892029.html

http://blog.sina.com.cn/s/blog_67aaf4440101628t.html

posted on 2013-08-09 09:06  chen110xi  阅读(187)  评论(0编辑  收藏  举报