学习了android ContentProvider ,现做学习笔记,参考了http://blog.sina.com.cn/s/blog_5688414b0100xagp.html的知识概念。
一、ContentProvider基本概念
1、ContentProvider为存储和获取数据提供了统一的接口。ContentProvide对数据进行封装,不用关心数据存储的细节。使用表的形式来组织数据。
2、使用ContentProvider可以在不同的应用程序之间共享数据。
3、Android为常见的一些数据提供了默认的ContentProvider(包括音频、视频、图片和通讯录等)。
ContentProvider所提供的函数:query(),insert(),update(),delete(),getType(),onCreate()等。
为系统的每一个资源给其一个名字,比方说通话记录。
1、每一个ContentProvider都拥有一个公共的URI,这个URI用于表示这个ContentProvider所提供的数据。
2、Android所提供的ContentProvider都存放在android.provider包中。
A:标准前缀,用来说明一个Content Provider控制这些数据,无法改变的;"content://"
C:路径,通俗的讲就是你要操作的数据库中表的名字,或者你也可以自己定义,记得在使用的时候保持一致
D:如果URI中包含表示需要获取的记录的ID;则就返回该id对应的数据,如果没有ID,就表示返回全部;"content://hx.android.text.myprovider/tablename/#"#表示数据id
三、ContentProvider的实现过程
自己实现ContentProvider不常见,因为可能不需要和别的应用程序交换数据。使用内置的ContentProvider比较多。
public static final Uri CONTENT_URI = Uri.parse("content://com.example.codelab.transportationprovider");
其中:content是协议
Uri.parse将一个字符串转换成Uri类型。
如果Provider包含子表,同样定义包含字表的CONTENT_URI。
content://com.example.codelab.transportationprovider/train
content://com.example.codelab.transportationprovider/air/domestic
content://com.example.codelab.transportationprovider/air/international
然后定义列,确保里面包含一个_id的列。
publicclass FirstContentProvider extends ContentProvider
先介绍一下ContentProvider用到的UriMatcher。UriMatcher的一个重要的函数是match(Uri uri)。这个函数可以匹配Uri,根据传入的不同Uri返回不同的自定义整形值,以表明Uri访问的不同资源的类型。
/**
*
*/
package edu.fjnu.sqlite;
import edu.fjnu.sqlite.service.DBOpenHelper;
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;
/**
* @author Kysann
*
*/
public class StudentProvider extends ContentProvider {
private DBOpenHelper dbOpenHelp = null;
private static final int STUDENTS = 1;
private static final int STUDENT = 2;
private static final UriMatcher MATCHER = new UriMatcher(UriMatcher.NO_MATCH);//UriMatcher.NO_MATCH 为 -1
static{
MATCHER.addURI("edu.fjnu.providers.studentprovider", "student", STUDENTS);
MATCHER.addURI("edu.fjnu.providers.studentprovider", "student/#", STUDENT);
}
@Override
public int delete(Uri uri, String whereClause, String[] whereArgs) {
SQLiteDatabase db =dbOpenHelp.getWritableDatabase();
int count = 0;
switch (MATCHER.match(uri)) {
case STUDENTS:
count = db.delete("student", whereClause, whereArgs);
break;
case STUDENT:
long id = ContentUris.parseId(uri);
String where = "_id=" + id;
if(whereClause != null && !"".equals(whereClause))
where = whereClause + "and" + where;
count = db.delete("student", where, whereArgs);
break;
default:
throw new IllegalArgumentException("Unknow uri :" + uri.toString());
}
return count;
}
@Override
public String getType(Uri uri) {
switch (MATCHER.match(uri)) {
case STUDENTS:
return "vnd.android.cursor.dir/student";
case STUDENT:
return "vnd.android.cursor.item/student";
default:
throw new IllegalArgumentException("Unknow uri :" + uri.toString());
}
}
/*
* uri :content://edu.fjnu.providers.studentprovider/student
* 插入一条学生记录
*/
@Override
public Uri insert(Uri uri, ContentValues values) {
SQLiteDatabase db = dbOpenHelp.getWritableDatabase();
switch (MATCHER.match(uri)) {
case STUDENTS:
long rowId = db.insert("student", "name", values);
Uri insertUri = ContentUris.withAppendedId(uri, rowId);
this.getContext().getContentResolver().notifyChange(uri, null);//更改监听
return insertUri;
default:
throw new IllegalArgumentException("Unknow uri = " + uri.toString());
}
}
@Override
public boolean onCreate() {
dbOpenHelp = new DBOpenHelper(this.getContext());
return false;
}
@Override
public Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder) {
SQLiteDatabase db = dbOpenHelp.getReadableDatabase();
Cursor cursor = null;
switch (MATCHER.match(uri)) {
case STUDENTS:
cursor = db.query("student", projection, selection, selectionArgs, null, null, sortOrder);
break;
case STUDENT:
long id = ContentUris.parseId(uri);
String where = "_id=" + id;
if(selection != null && !"".equals(selection))
where = selection + "and" + where;
cursor = db.query("student", projection, where, selectionArgs, null, null, sortOrder);
break;
default:
throw new IllegalArgumentException("Unknow uri : " + uri.toString());
}
return cursor;
}
@Override
public int update(Uri uri, ContentValues values, String selection,
String[] selectionArgs) {
SQLiteDatabase db = dbOpenHelp.getWritableDatabase();
int count = 0;
switch (MATCHER.match(uri)) {
case STUDENTS:
count = db.update("student", values, null, null);
break;
case STUDENT:
long id = ContentUris.parseId(uri);
String where = "_id=" + id;
if(selection != null && !"".equals(selection))
where = selection + "and" +where;
count = db.update("student", values, where, selectionArgs);
break;
default:
throw new IllegalArgumentException("Unknow uri = " + uri.toString());
}
return count;
}
}
<provider
android:exported="true"
android:name="edu.fjnu.sqlite.StudentProvider"
android:authorities="edu.fjnu.providers.studentprovider">
</provider>
5、在另外一个应用程序中使用ContentProvider中注册监听,使用 用ContentResolver操作。
public class HelloActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView tv = new TextView(this);
tv.setText("Hello Android,Hello World");
setContentView(tv);
Uri insertUri = Uri.parse("content://edu.fjnu.providers.studentprovider/student");
ContentResolver contentResolver = getContentResolver();
contentResolver.registerContentObserver(insertUri, true, new Observer(new Handler()));
}
private final class Observer extends ContentObserver{ //观察者类
public Observer(Handler handler) {
super(handler);
// TODO Auto-generated constructor stub
}
@Override
public void onChange(boolean selfChange) {
ContentResolver contentResolver = getContentResolver();
Uri uri = Uri.parse("content://edu.fjnu.providers.studentprovider/student");
Cursor cursor = contentResolver.query(uri, null, null, null, "_id desc");
while(cursor.moveToNext()){
//Integer id = cursor.getInt(cursor.getColumnIndex("_id"));
String name = cursor.getString(cursor.getColumnIndex("stu_name"));
//String pwd = cursor.getString(cursor.getColumnIndex("stu_pwd"));
Toast.makeText(HelloActivity.this, name, Toast.LENGTH_SHORT).show();
}
}
}