http://blog.csdn.net/woshixuye/article/details/8280879

实例代码
当数据需要在应用程序间共享时,我们就可以利用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; /**
* contentProvider作为一种组件必须放在应用所在包或其子包下,主要作用是对外共享数据
* 测试步骤1:将本项目先部署
* 测试步骤2:调用测试方法
* @author xy
*
*/
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);
}
} /**
* 返回对应的内容类型
* 如果返回集合的内容类型,必须以vnd.android.cursor.dir开头
* 如果是单个元素,必须以vnd.android.cursor.item开头
*/
@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; /**
* 测试代码
* @author xy
*
*/
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();
}
}

contentProvider 内容提供者的更多相关文章

  1. Android组件系列----ContentProvider内容提供者

    [声明] 欢迎转载,但请保留文章原始出处→_→ 生命壹号:http://www.cnblogs.com/smyhvae/ 文章来源:http://www.cnblogs.com/smyhvae/p/4 ...

  2. android 53 ContentProvider内容提供者

    ContentProvider内容提供者:像是一个中间件一样,一个媒介一样,可以以标准的增删改差操作对手机的文件.数据库进行增删改差.通过ContentProvider查找sd卡的音频文件,可以提供标 ...

  3. contentProvider内容提供者

    contentProvider内容提供者 15. 四 / android基础 / 没有评论   步骤 权限在application中注册 Source code     <provider an ...

  4. android contentprovider内容提供者

    contentprovider内容提供者:让其他app可以访问私有数据库(文件) 1.AndroidManifest.xml 配置provider <?xml version="1.0 ...

  5. Android组件系列----ContentProvider内容提供者【1】

    [正文] 一.ContentProvider简单介绍: ContentProvider内容提供者(四大组件之中的一个)主要用于在不同的应用程序之间实现数据共享的功能. ContentProvider能 ...

  6. Android开发学习—— ContentProvider内容提供者

    * 应用的数据库是不允许其他应用访问的* 内容提供者的作用就是让别的应用访问到你的数据库.把私有数据暴露给其他应用,通常,是把私有数据库的数据暴露给其他应用. Uri:包含一个具有一定格式的字符串的对 ...

  7. Android -- ContentProvider 内容提供者,创建和调用

    1. 概述 ContentProvider 在android中的作用是对外共享数据,也就是说你可以通过ContentProvider把应用中的数据共享给其他应用访问,其他应用可以通过ContentPr ...

  8. Android 进阶11:进程通信之 ContentProvider 内容提供者

    学习启舰大神,每篇文章写一句励志的话,与大家共勉. When you are content to be simply yourself and don't compare or compete, e ...

  9. Android组件系列----ContentProvider内容提供者【4】

    (4)单元測试类: 这里须要涉及到另外一个知识:ContentResolver内容訪问者. 要想訪问ContentProvider.则必须使用ContentResolver. 能够通过ContentR ...

随机推荐

  1. liunx之:rpm包安装

    使用rpm命令查询软件包: 1.查询系统中安装的所有RPM包 $ rpm -qa 查询当前linux系统中已经安装的软件包. 例:$ rpm -qa | grep -i x11 | head -3 察 ...

  2. gcc: multiple definition of [转]

    /home/tace/openav/source/SeamlessMessage/CPaoFlt.o: In function `CPaoFlt::get_m_strPrmair() const':C ...

  3. soap的简单实现(PHP)

    1.非wsdl模式 (1)函数文件 testphp/ServiceFunctions.class.php <?php /** * @author 左小兵 * */ class ServiceFu ...

  4. Windows动态链接库DLL

    1.什么是DLLDLL,即动态链接库,是包含若干个函数的库文件,可供其他程序运行时调用. 2.DLL的优缺点优点:代码重用,可供多个程序同时调用 缺点:易发生版本冲突当新版本的动态链接库不兼容旧版本时 ...

  5. hibernate--HQL语法与详细解释

    HQL查询: Criteria查询对查询条件进行了面向对象封装,符合编程人员的思维方式,不过HQL(Hibernate Query Lanaguage)查询提供了更加丰富的和灵活的查询特性,因此 Hi ...

  6. Java 实现任意N阶幻方的构造

    一.关于单偶数阶幻方和双偶数阶幻方 (一)单偶数阶幻方(即当n=4k+2时) 任何4k+2 阶幻方都可由2k+1阶幻方与2×2方块复合而成,6是此类型的最小阶. 以6阶为例,可由3阶幻方与由0,1,2 ...

  7. postfix

    http://www.postfix.org/ All programmers are optimists -- Frederick P. Brooks, Jr. 所有程序员都是乐天派

  8. SQL中 EXCEPT、INTERSECT用法

    EXCEPT 返回两个结果集的差(即从左查询中返回右查询没有找到的所有非重复值). INTERSECT 返回 两个结果集的交集(即两个查询都返回的所有非重复值). UNION返回两个结果集的并集. 语 ...

  9. mysql toolkit 用法[备忘] (转)

    命令列表 /usr/bin/pt-agent /usr/bin/pt-align /usr/bin/pt-archiver /usr/bin/pt-config-diff /usr/bin/pt-de ...

  10. Linux下Memcached-1.4.10安装

    memcache是一款流行的缓存产品,它分为两个部分:一个是运行在服务器端的memcached进程,一个是在客户端进行调用获取缓存中数据客户端,例如比较常用的PHP客户端.这里,记录一下安装服务器端的 ...