Android内容提供者ContentProvider用法实例分析
作者:Ruthless 发布时间:2021-06-25 09:33:04
标签:Android,内容提供者,ContentProvider
本文实例讲述了Android内容提供者ContentProvider用法。分享给大家供大家参考,具体如下:
PersonContentProvider内容提供者类
package com.ljq.db;
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.text.TextUtils;
/**
* 内容提供者
*
* 作用:统一数据访问方式,方便外部调用
*
* @author jiqinlin
*
*/
public class PersonContentProvider extends ContentProvider {
// 数据集的MIME类型字符串则应该以vnd.android.cursor.dir/开头
public static final String PERSONS_TYPE = "vnd.android.cursor.dir/person";
// 单一数据的MIME类型字符串应该以vnd.android.cursor.item/开头
public static final String PERSONS_ITEM_TYPE = "vnd.android.cursor.item/person";
public static final String AUTHORITY = "com.ljq.provider.personprovider";// 主机名
/* 自定义匹配码 */
public static final int PERSONS = 1;
/* 自定义匹配码 */
public static final int PERSON = 2;
public static final Uri PERSONS_URI = Uri.parse("content://" + AUTHORITY + "/person");
private DBOpenHelper dbOpenHelper = null;
// UriMatcher类用来匹配Uri,使用match()方法匹配路径时返回匹配码
private static final UriMatcher uriMatcher;
static {
// 常量UriMatcher.NO_MATCH表示不匹配任何路径的返回码
uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
// 如果match()方法匹配content://com.ljq.provider.personprovider/person路径,返回匹配码为PERSONS
uriMatcher.addURI(AUTHORITY, "person", PERSONS);
// 如果match()方法匹配content://com.ljq.provider.personprovider/person/230路径,返回匹配码为PERSON
uriMatcher.addURI(AUTHORITY, "person/#", PERSON);
}
@Override
public boolean onCreate() {
dbOpenHelper = new DBOpenHelper(this.getContext());
return true;
}
@Override
public Uri insert(Uri uri, ContentValues values){
SQLiteDatabase db = dbOpenHelper.getWritableDatabase();
long id = 0;
switch (uriMatcher.match(uri)) {
case PERSONS:
id = db.insert("person", "name", values);// 返回的是记录的行号,主键为int,实际上就是主键值
return ContentUris.withAppendedId(uri, id);
case PERSON:
id = db.insert("person", "name", values);
String path = uri.toString();
return Uri.parse(path.substring(0, path.lastIndexOf("/"))+id); // 替换掉id
default:
throw new IllegalArgumentException("Unknown URI " + uri);
}
}
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
SQLiteDatabase db = dbOpenHelper.getWritableDatabase();
int count = 0;
switch (uriMatcher.match(uri)) {
case PERSONS:
count = db.delete("person", selection, selectionArgs);
break;
case PERSON:
// 下面的方法用于从URI中解析出id,对这样的路径content://com.ljq.provider.personprovider/person/10
// 进行解析,返回值为10
long personid = ContentUris.parseId(uri);
String where = "id=" + personid;// 删除指定id的记录
where += !TextUtils.isEmpty(selection) ? " and (" + selection + ")" : "";// 把其它条件附加上
count = db.delete("person", where, selectionArgs);
break;
default:
throw new IllegalArgumentException("Unknown URI " + uri);
}
db.close();
return count;
}
@Override
public int update(Uri uri, ContentValues values, String selection,
String[] selectionArgs) {
SQLiteDatabase db = dbOpenHelper.getWritableDatabase();
int count = 0;
switch (uriMatcher.match(uri)) {
case PERSONS:
count = db.update("person", values, selection, selectionArgs);
break;
case PERSON:
// 下面的方法用于从URI中解析出id,对这样的路径content://com.ljq.provider.personprovider/person/10
// 进行解析,返回值为10
long personid = ContentUris.parseId(uri);
String where = "id=" + personid;// 获取指定id的记录
where += !TextUtils.isEmpty(selection) ? " and (" + selection + ")" : "";// 把其它条件附加上
count = db.update("person", values, where, selectionArgs);
break;
default:
throw new IllegalArgumentException("Unknown URI " + uri);
}
db.close();
return count;
}
@Override
public String getType(Uri uri) {
switch (uriMatcher.match(uri)) {
case PERSONS:
return PERSONS_TYPE;
case PERSON:
return PERSONS_ITEM_TYPE;
default:
throw new IllegalArgumentException("Unknown URI " + uri);
}
}
@Override
public Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder) {
SQLiteDatabase db = dbOpenHelper.getReadableDatabase();
switch (uriMatcher.match(uri)) {
case PERSONS:
return db.query("person", projection, selection, selectionArgs, null, null, sortOrder);
case PERSON:
// 下面的方法用于从URI中解析出id,对这样的路径content://com.ljq.provider.personprovider/person/10
// 进行解析,返回值为10
long personid = ContentUris.parseId(uri);
String where = "id=" + personid;// 获取指定id的记录
where += !TextUtils.isEmpty(selection) ? " and (" + selection + ")" : "";// 把其它条件附加上
return db.query("person", projection, where, selectionArgs, null, null, sortOrder);
default:
throw new IllegalArgumentException("Unknown URI " + uri);
}
}
}
文件清单
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.ljq.sql" android:versionCode="1"
android:versionName="1.0">
<application android:icon="@drawable/icon"
android:label="@string/app_name">
<uses-library android:name="android.test.runner" />
<activity android:name=".SqlActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category
android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<provider android:name="com.ljq.db.PersonContentProvider"
android:authorities="com.ljq.provider.personprovider" />
</application>
<uses-sdk android:minSdkVersion="7" />
<instrumentation
android:name="android.test.InstrumentationTestRunner"
android:targetPackage="com.ljq.sql" android:label="Tests for My App" />
</manifest>
PersonContentProviderTest内容提供者测试类
package com.ljq.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 jiqinlin
*
*/
public class PersonContentProviderTest extends AndroidTestCase{
private static final String TAG = "PersonContentProviderTest";
public void testSave() throws Throwable{
ContentResolver contentResolver = this.getContext().getContentResolver();
Uri insertUri = Uri.parse("content://com.ljq.provider.personprovider/person");
ContentValues values = new ContentValues();
values.put("name", "ljq");
values.put("phone", "1350000009");
Uri uri = contentResolver.insert(insertUri, values);
Log.i(TAG, uri.toString());
}
public void testUpdate() throws Throwable{
ContentResolver contentResolver = this.getContext().getContentResolver();
Uri updateUri = Uri.parse("content://com.ljq.provider.personprovider/person/1");
ContentValues values = new ContentValues();
values.put("name", "linjiqin");
contentResolver.update(updateUri, values, null, null);
}
public void testFind() throws Throwable{
ContentResolver contentResolver = this.getContext().getContentResolver();
//Uri uri = Uri.parse("content://com.ljq.provider.personprovider/person");
Uri uri = Uri.parse("content://com.ljq.provider.personprovider/person");
Cursor cursor = contentResolver.query(uri, null, null, null, "id asc");
while(cursor.moveToNext()){
int personid = cursor.getInt(cursor.getColumnIndex("id"));
String name = cursor.getString(cursor.getColumnIndex("name"));
String phone = cursor.getString(cursor.getColumnIndex("phone"));
Log.i(TAG, "personid="+ personid + ",name="+ name+ ",phone="+ phone);
}
cursor.close();
}
public void testDelete() throws Throwable{
ContentResolver contentResolver = this.getContext().getContentResolver();
Uri uri = Uri.parse("content://com.ljq.provider.personprovider/person/1");
contentResolver.delete(uri, null, null);
}
}
希望本文所述对大家Android程序设计有所帮助。


猜你喜欢
- CircuitBreaker 断路器服务熔断是为了保护我们的服务,比如当某个服务出现问题的时候,控制打向它的流量,让它有时间去恢复,或者限制
- 这篇实例中有四个类,分别为CacheItem 缓存实体类CachePool 缓存池Student 学生实
- 前言在日常的测试工作过程中,app可能会出现闪退崩溃的情况,这个时候就需要测试同学快速抓取到崩溃日志,来有效的辅助开发定位问题,快速的去解决
- mybatis获取表中某一列的最大值这个问题这两天也是找了好久才找到解决办法,在此记录一下。获取表中数据某一列的最大值,在mapper.xm
- import java.io.FileNotFoundException;import java.io.FileOutputStream;i
- C#利用缓存分块读写大文件,供大家参考,具体内容如下在日常生活中,可能会遇到大文件的读取,不论是什么格式,按照储存文件的格式读取大文件,就会
- 前言在我们做后端服务Dao层开发,特别是大数据批量插入的时候,这时候普通的ORM框架(Mybatis、hibernate、JPA)就无法满足
- /// <summary>/// 获取数据缓存/// </summary>/// <param name=&q
- 1. strlen —— 求字符串长度1.1 strlen 的声明与用处strlen ,我们有一些英
- 布局管理器在java.awt 包中提供了5中常用的布局管理器,分别式FlowLayout(流式布局管理器)、BorderLayout(边界布
- 要使用Dictionary集合,需要导入C#泛型命名空间 System.Collections.Generic(程序集:mscor
- 我就废话不多说啦,大家还是直接看代码吧~[ { "orderNo": "3213123123123
- 数学原理:  
- 接收 / 返回文本消息①接收/返回文本消息原理说明当普通微信用户向公众账号发消息时,微信服务器将POST消息的XML数据包到开发者填写的UR
- public class PullToLoadListView extends ListView implements OnScrollLi
- 1,验证传入路径是否为正确的路径名(Windows系统,其他系统未使用)Java代码 // 验证字符串是否为正确路径名的正则表达式 
- Jackson反序列化遇到的问题最近在项目中需要使用Jackson把前台转来的字符转为对象,转换过程中发生了错误,报错如下com.faste
- 前言大家好,我是bigsai,在数据结构与算法中,二叉树无论是考研、笔试都是非常高频的考点内容,在二叉树中,二叉树的遍历又是非常重要的知识点
- import java.util.ArrayList;import java.util.HashMap;import java.util.I
- 上周五东西都收拾好了,然后被叫住加班,直接搞到凌晨一两点,原因是另一个项目的性能出了点问题。为此我抓包写了一下主业务流的接口,涉及到文件上传