首先介绍一下android的ContentProvider的具体含义:
当应用继承ContentProvider类,并重写该类用于提供数据和存储数据的方法,就可以向其他应用共享其数据。虽然使用其他方法也可以对外共享数据,但数据访问方式会因数据存储的方式而不同,如:采用文件方式对外共享数据,需要进行文件操作读写数据;采用sharedpreferences共享数据,需要使用sharedpreferences API读写数据。而使用ContentProvider共享数据的好处是统一了数据访问方式。
.适用场景
1) ContentProvider为存储和读取数据提供了统一的接口
2) 使用ContentProvider,应用程序可以实现数据共享
3) android内置的许多数据都是使用ContentProvider形式,供开发者调用的(如视频,音频,图片,通讯录等)
2.相关概念介绍
public class DbHeler extends SQLiteOpenHelper{
private static String name="mydb.db";
private static int version=1;
public DbHeler(Context context) {
super(context,name, null,version);
// TODO Auto-generated constructor stub
}
@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
String sql="create table student (id integer primary key autoincrement ,name varchar(64),address varchar(64))";
db.execSQL(sql);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
}
工具类写好了,下面是主要的内容提供者的主要的类
public class StudentProvider extends ContentProvider {
private final String TAG = "StudentProvider";
private DbHeler helper = null;
private static final UriMatcher URI_MATCHER = new UriMatcher(
UriMatcher.NO_MATCH);
private static final int STUDENT = 1;
private static final int STUDENTS = 2;
static {
URI_MATCHER.addURI("com.example.contentprovider.StudentProvider",
"student", STUDENTS);
URI_MATCHER.addURI("com.example.contentprovider.StudentProvider",
"student/#", STUDENT);
}
@Override
public Uri insert(Uri uri, ContentValues values) {
// TODO Auto-generated method stub
Uri resultUri = null;
int flag = URI_MATCHER.match(uri);
switch (flag) {
case STUDENTS:
SQLiteDatabase database = helper.getWritableDatabase();
long id = database.insert("student", null, values);
resultUri = ContentUris.withAppendedId(uri, id);
break;
default:
break;
}
Log.i(TAG, "---->" + resultUri.toString());
return resultUri;
}
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
int count=-1;//影响数据库的行数
try {
int flag=URI_MATCHER.match(uri);
SQLiteDatabase database=helper.getWritableDatabase();
switch (flag) {
case STUDENT:
//content://com.example.contentprovider.StudentProvider/student/1
//delete from student where id=?
long id=ContentUris.parseId(uri);
String where_value=" id = "+id;
if(selection!=null&&!selection.equals("")){
where_value+=" and "+selection;
}
count =database.delete("student", where_value, selectionArgs);
break;
case STUDENTS:
count=database.delete("student", selection,selectionArgs);
break;
default:
break;
}
} catch (Exception e) {
// TODO: handle exception
}
return 0;
}
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
String sortOrder) {
Cursor cursor=null;
try {
SQLiteDatabase database=helper.getReadableDatabase();
int flag=URI_MATCHER.match(uri);
switch (flag) {
case STUDENT:
long id=ContentUris.parseId(uri);
String where_value=" id = "+id;
if(selection!=null&&!selection.equals("")){
where_value+=" and "+selection;
}
cursor=database.query("student", null, where_value, selectionArgs, null, null, null, null);
break;
case STUDENTS:
cursor=database.query("student", null, selection,selectionArgs, null, null, null, null);
break;
default:
break;
}
} catch (Exception e) {
// TODO: handle exception
}
return cursor;
}
@Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
int count=-1;
try {
SQLiteDatabase database=helper.getWritableDatabase();
//update table set name=? ,address=? values id=?
long id=ContentUris.parseId(uri);
int flag=URI_MATCHER.match(uri);
switch (flag) {
case STUDENT:
String where_value=" id = "+id;
if(selection!=null&&!selection.equals("")){
where_value+=" and "+selection;
}
count=database.update("student", values, where_value, selectionArgs);
break;
default:
break;
}
} catch (Exception e) {
// TODO: handle exception
}
return count;
}
@Override
public boolean onCreate() {
helper = new DbHeler(getContext());
return false;
}
@Override
public String getType(Uri uri) {
int flag = URI_MATCHER.match(uri);
switch (flag) {
case STUDENT:
return "vnd.android.cursor.item/student";
case STUDENTS:
return "vnd.android.cursor.dir/students";
}
return null;
}
}
写一个测试类把,来测试所有的接口
public class MyTest extends AndroidTestCase {
public void insert() {
// 内容解析者
ContentResolver contentResolver = getContext().getContentResolver();
Uri url = Uri
.parse("content://com.example.contentprovider.StudentProvider/student");
ContentValues values = new ContentValues();
values.put("name", "王五");
values.put("address", "济南");
contentResolver.insert(url, values);
}
public void delete() {
ContentResolver contentResolver = getContext().getContentResolver();
Uri uri = Uri
.parse("content://com.example.contentprovider.StudentProvider/student/2");
contentResolver.delete(uri, null, null);
}
public void update() {
ContentResolver contentResolver = getContext().getContentResolver();
Uri uri = Uri
.parse("content://com.example.contentprovider.StudentProvider/student/3");
ContentValues values=new ContentValues();
values.put("name","李斯");
values.put("address","上海");
contentResolver.update(uri, values, null, null);
}
public void query(){
ContentResolver contentResolver=getContext().getContentResolver();
//查询单条记录://com.example.contentprovider.StudentProvider/student/3
//查询多条记录: content://com.example.contentprovider.StudentProvider/student
Uri uri = Uri
.parse("content://com.example.contentprovider.StudentProvider/student");
Cursor cursor=contentResolver.query(uri, null, null, null, null);
while(cursor.moveToNext()){
System.out.println("--->"+cursor.getString(cursor.getColumnIndex("name")));
}
}
}
最后的配置文件
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.contentprovider"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<instrumentation android:name="android.test.InstrumentationTestRunner"
android:targetPackage="com.example.contentprovider"></instrumentation>
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<uses-library android:name="android.test.runner"/>
<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>
</activity>
<provider
android:name=".StudentProvider"
android:authorities="com.example.contentprovider.StudentProvider"
></provider>
</application>
</manifest>