http://blog.chinaunix.net/uid-24129645-id-3758633.html
一、什么是ContentProvider?
ContentProvider是一个抽象类,可以理解为一个特殊的存储数据的类型,它提供了一套标准的接口来获取和操作数据。可以把数据封装到ContentProvider 中,从而是这些数据可以被其他的应用程序所共享。搭建起了所有应用程序之间数据交换的桥梁!
二、ContentProvider的创建过程
1.创建一个类继承ContentProvider
继承它需要实现其所有的抽象方法
a.onCreate() :初始化该ContentProvider
b.query(Uri,String[],String,Sring[],String) :通过Uri进行查询,返回Uri
c.intert(Uri,ContentValues):将数据插入到Uri所指定的位置
d.update(Uri,ContentValues,String,String []):更新uri指定位置的数据
e.delete(Uri,String,String[]):删除uri指定位置的数据
f.getType(Uri):返回数据的类型
2.声明CONTENT_URI,实现UriMatcher
每个ContentProvider都会对外提供一个公共的Uri,当有数据共享的时候,就需要使用ContentProvider为这些数据定义一个Uri,
UriMatcher是一个用来匹配Uri的工具类
public static final String AUTHORITY="com.example.provider.students";
private static final UriMatcher Urimatcher;
Urimatcher=new UriMatcher(UriMatcher.NO_MATCH);
//添加需要匹配的Uri,匹配则返回相应的匹配码
Urimatcher.addURI(Students.AUTHORITY, "student", STUDENT);
Urimatcher.addURI(Students.AUTHORITY, "student/#", STUDENT_ID);
3.在AndroidManifest.xml中注册
<provider
android:name=".StudentContentProvider"
android:authorities="com.example.provider.students"
/>
三、ContentProvider的使用实例
1.常量类,声明需要使用的常量
点击(此处)折叠或打开
- package com.example.provider;
- import android.net.Uri;
- import android.provider.BaseColumns;
- /**
- *
- * @author zt
- *常量类,声明要使用的常量
- *内部类Student实现了BaseColumns接口,该接口也是一个常量接口
- 该常量接口中已经定义了_id和_count常量,分别用来表示记录的id和已经记录的数量
- */
- public final class Students {
- //定义常量
- public static final String AUTHORITY="com.example.provider.students";
- private Students(){}
- //内部类
- public static final class Student implements BaseColumns{
- private Student(){} //构造方法
- public static final Uri CONTENT_URI=Uri.parse("content://"+AUTHORITY+"/student");
- public static final String CONTENT_TYPE="vnd.android.cursor.dir/vnd.example.provider.students";
- public static final String CONTENT_ITEM_TYPE="vnd.android.cursor.item/vnd.example.provider.students";
- //数据库中的表字段
- public static final String NMAE="name";//姓名
- public static final String GENDER="gender";//性别
- public static final String AGE="age";//年龄
- }
- }
2.利用数据库帮助类SQLiteOpenHelper来创建数据库
点击(此处)折叠或打开
- package com.example.provider;
- import com.example.provider.Students.Student;
- import android.content.Context;
- import android.database.sqlite.SQLiteDatabase;
- import android.database.sqlite.SQLiteOpenHelper;
- public class DbHelper extends SQLiteOpenHelper {
- //数据库的名称
- private static final String DATABASE_NAME="student.db";
- private static final int DATABASE_VERSION=1;
- public static final String TABLE_NAME="student";
-
- public DbHelper(Context context) {
- super(context, DATABASE_NAME, null, DATABASE_VERSION);
-
- }
- /**
- * 创建table
- */
- @Override
- public void onCreate(SQLiteDatabase db) {
- //创建学生信息表,包括四个字段
- //包括id、姓名、性别、年龄
- String sql="create table "+TABLE_NAME+" ("
- +Student._ID+" integer primary key,"
- +Student.NMAE+" text,"
- +Student.GENDER+" text,"
- +Student.AGE+" integer "+");";
- db.execSQL(sql);
- }
- /**
- * 更新表
- */
- @Override
- public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
-
- String sql="drop table if exits student";
- db.execSQL(sql);
- }
- }
3.创建StudentContentProvider类继承ContentProvider
点击(此处)折叠或打开
- package com.example.provider;
- import java.util.HashMap;
- import com.example.provider.Students.Student;
- import android.content.ContentProvider;
- import android.content.ContentResolver;
- 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;
- public class StudentContentProvider extends ContentProvider {
-
- //声明数据库帮助类对象
- private DbHelper dbHelper;
- //定义ContentResolver 对象
- private ContentResolver resolver;
- //定义Uri工具类
- private static final UriMatcher Urimatcher;
- //匹配码
- private static final int STUDENT=1;
- private static final int STUDENT_ID=2;
- //需要查询 的列集合
- private static HashMap<String,String> stu;
- //
-
- static
- {
- Urimatcher=new UriMatcher(UriMatcher.NO_MATCH);
- //添加需要匹配的Uri,匹配则返回相应的匹配码
- Urimatcher.addURI(Students.AUTHORITY, "student", STUDENT);
- Urimatcher.addURI(Students.AUTHORITY, "student/#", STUDENT_ID);
- //实例化集合
- stu=new HashMap<String,String>();
- //添加查询列map
- stu.put(Student._ID, Student._ID);
- stu.put(Student.NMAE,Student.NMAE );
- stu.put(Student.GENDER, Student.GENDER);
- stu.put(Student.AGE,Student.AGE );
- }
-
- /**
- * 初始化
- */
- @Override
- public boolean onCreate() {
- //创建DbHelper对象
- dbHelper=new DbHelper(getContext());
- return true;
- }
- /**
- * 查询数据
- */
- @Override
- public Cursor query(Uri uri, String[] projection, String selection,
- String[] selectionArgs, String sortOrder) {
-
- SQLiteDatabase db=dbHelper.getReadableDatabase();
- Cursor cursor;
- switch(Urimatcher.match(uri))
- {
- case STUDENT:
- cursor=db.query(DbHelper.TABLE_NAME,projection , selection,
- selectionArgs, null, null, sortOrder);
- break;
- case STUDENT_ID:
- String stuId=uri.getPathSegments().get(1);
- String where="Student._ID="+stuId;
- if(selection!=null&&"".equals(selection.trim()))//trim()函数的功能是去掉首尾空格
- {
- where+=" and "+selection;
- }
- cursor=db.query(DbHelper.TABLE_NAME, projection, where, selectionArgs, null, null, sortOrder);
- break;
- default:
- //如果传进来的Uri不是我们需要的类型
- throw new IllegalArgumentException("this is Unknown Uri:"+uri);
- }
- return cursor;
- }
- /**
- * 获得类型
- */
- @Override
- public String getType(Uri uri) {
-
-
- return null;
- }
- /**
- * 插入数据
- */
- @Override
- public Uri insert(Uri uri, ContentValues values) {
-
- //获得可写入的数据库
- SQLiteDatabase db=dbHelper.getWritableDatabase();
- ContentResolver resolver=this.getContext().getContentResolver();
- //插入数据,返回行号ID
- long rowid=db.insert(DbHelper.TABLE_NAME, Student.NMAE, values);
- //如果插入成功,返回Uri
- if(rowid>0)
- {
- Uri stuUri=ContentUris.withAppendedId(uri, rowid);
- resolver.notifyChange(stuUri, null);//数据发送变化时候,发出通知给注册了相应uri的
- return stuUri;
- }
- return null;
- }
- /**
- * 删除数据
- */
- @Override
- public int delete(Uri uri, String selection, String[] selectionArgs) {
-
- SQLiteDatabase db=dbHelper.getWritableDatabase();
- resolver=this.getContext().getContentResolver();
- int count;
- //根据返回的匹配码进行相应的删除动作
- switch(Urimatcher.match(uri))
- {
- case STUDENT:
- count=db.delete(DbHelper.TABLE_NAME, selection, selectionArgs);
- break;
- case STUDENT_ID: //只删除对于的id
- //getPathSegments()方法得到一个String的List
- String stuId=uri.getPathSegments().get(1);
- count=db.delete(DbHelper.TABLE_NAME, Student._ID+"="+stuId+(!TextUtils.isEmpty(selection) ?
- " and ("+selection+')':""), selectionArgs);
- break;
- default:
- //如果传进来的Uri不是我们需要的类型
- throw new IllegalArgumentException("this is Unknown Uri:"+uri);
- }
- resolver.notifyChange(uri, null);
- return count;
- }
- /**
- * 更新数据
- */
- @Override
- public int update(Uri uri, ContentValues values, String selection,
- String[] selectionArgs) {
-
- SQLiteDatabase db=dbHelper.getWritableDatabase();//创建一个可读的数据库
- resolver=this.getContext().getContentResolver();
- int count;
- switch(Urimatcher.match(uri))
- {
- case STUDENT:
- count=db.update(DbHelper.TABLE_NAME, values, selection, selectionArgs);
- break;
- case STUDENT_ID:
- String stuId=uri.getPathSegments().get(1);//获得id
- count=db.update(DbHelper.TABLE_NAME, values,Student._ID+"="+stuId+(!TextUtils.isEmpty(selection) ?
- " and ("+selection+')':""), selectionArgs);
- break;
- default:
- //如果传进来的Uri不是我们需要的类型
- throw new IllegalArgumentException("this is Unknown Uri:"+uri);
- }
- resolver.notifyChange(uri, null);
- return count;
- }
- }
4.创建一个Activity 来测试,查询、删减、插入、更新数据
点击(此处)折叠或打开
- package com.example.provider;
- import com.example.provider.Students.Student;
- import android.app.Activity;
- import android.content.ContentResolver;
- import android.content.ContentUris;
- import android.content.ContentValues;
- import android.database.Cursor;
- import android.net.Uri;
- import android.os.Bundle;
- import android.util.Log;
- public class MyContentProvider extends Activity {
-
- private static final String TAG="MyContentProvider";
- private ContentResolver resolver;
-
- @Override
- protected void onCreate(Bundle savedInstanceState)
- {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- insert();//插入数据
- // delete(1);//删除第一行
- update(4);
- query();//查询
- }
- //插入数据
- public void insert()
- {
- Uri uri=Student.CONTENT_URI;
- //获得ContentResolver对象
- resolver=this.getContentResolver();
- ContentValues values=new ContentValues();
- //添加学生信息
- values.put(Student.NMAE, "Jack");
- values.put(Student.GENDER, "男");
- values.put(Student.AGE, 20);
- //将信息插入
- resolver.insert(uri, values);
- Log.i(TAG, uri.toString());
- }
- //删除数据
- //删除第id行
- public void delete(Integer id)
- {
- //指定uri
- Uri uri=ContentUris.withAppendedId(Student.CONTENT_URI, id);
- resolver=this.getContentResolver();
- resolver.delete(uri, null, null);
- }
- //更新
- public void update(Integer id)
- {
- Uri uri=ContentUris.withAppendedId(Student.CONTENT_URI, id);
- resolver=this.getContentResolver();
- ContentValues values=new ContentValues();
- values.put(Student.NMAE, "xiaofang");
- values.put(Student.GENDER, "女");
- values.put(Student.AGE, 25);
- resolver.update(uri, values, null, null);
- }
- //查询
- public void query()
- {
- Uri uri=Student.CONTENT_URI;
- String[] PROJECTION=new String[]{
- Student._ID,
- Student.NMAE,
- Student.GENDER,
- Student.AGE
- };
- resolver=this.getContentResolver();
- Cursor cursor=resolver.query(uri, PROJECTION, null, null, null);
- //判断游标是否为空
- if(cursor.moveToFirst())
- {
- for(int i=0;i<cursor.getCount();i++)
- {
- cursor.moveToPosition(i);
- int id=cursor.getInt(0);//获得id
- String name=cursor.getString(1);//取得姓名
- String gender=cursor.getString(2);//取得性别
- int age=cursor.getInt(3);//取得年龄
- //输出日记
- Log.i(TAG, "id:"+id+" name:"+name+" gender:"+gender+" age:"+age);
- }
- }
-
- }
- }
5.运行模拟器,测试结果如下:
总结:也可以通过其他的应用程序来访问该Activity的数据!