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. 整合UMDH结果的一个小工具

    ua.exe使用方法: 1.将UMDH生成的logcompare.txt改名为1.txt,内容示例: // Debug library initialized ... DBGHELP: moxia_d ...

  2. Textarea高度随内容自适应地增长,无滚动条

    <HTML> <HEAD> <meta http-equiv="Content-Type" content="text/html; char ...

  3. Oracle数据库——体系结构

    一.涉及内容 1.了解数据库的物理存储结构和逻辑存储结构 二.具体操作 1.分别使用SQL 命令和OEM 图形化工具查看本地数据库的物理文件,并使用OEM 工具在现有的users 表空间中添加user ...

  4. linux概念之内存分析

    linux内存总结 分析样本[root@-comecs ~]# free total used free shared buffers cached Mem: -/+ buffers/cache: S ...

  5. 九度OJ题目1387斐波那契数列

    /*斐波那契数列,又称黄金分割数列,指的是这样一个数列: 0.1.1.2.3.5.8.13.21.…… 在数学上,斐波纳契数列被定义如下: F0=0,F1=1, Fn=F(n-1)+F(n-2)(n& ...

  6. WebApiThrottle限流框架

    ASP.NET Web API Throttling handler is designed to control the rate of requests that clients can make ...

  7. php 安装shpinx扩展

    cd /home/packages wget http://sphinxsearch.com/files/sphinx-0.9.9.tar.gz tar xzvf sphinx-0.9.9.tar.g ...

  8. HackerRank "The Indian Job"

    A sly knapsack problem in disguise! Thanks to https://github.com/bhajunsingh/programming-challanges/ ...

  9. 清理SQL Server日志释放文件空间的终极方法

    清理SQL Server日志释放文件空间的终极方法  转自:http://www.cnblogs.com/dudu/archive/2013/04/10/3011416.html [问题场景]有一个数 ...

  10. postgresql数据库文件目录

    不同的发行版位置不同 查看进程 ps auxw | grep postgres | grep -- -D 找到默认的目录 /usr/lib/postgresql/9.4/bin/postgres -D ...