提供数据被访问的一方。
public class WordProvider extends ContentProvider {
private UriMatcher matcher;
private static final int MATCH_ROOT = 1;
private static final int MATCH_HELLO = 2;
@Override
public boolean onCreate() {
// 当本ContentProvider被创建时回调
// 第一步,创建UriMatcher对象
matcher = new UriMatcher(UriMatcher.NO_MATCH);
// 第二步,添加匹配的URI,并指定匹配时的返回值
//MATCH_ROOT MATCH_HELLO 就是返回值
matcher.addURI("cn.teee.providers.word", null, MATCH_ROOT);
matcher.addURI("cn.teee.providers.word", "hello", MATCH_HELLO);
return false;
}
// content://cn.teee.providers.word
// content://cn.teee.providers.word/hello
@Override
public Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder) {
// 当其它应用查询数据时回调
//第三步,与已经注册的URI进行匹配
switch (matcher.match(uri)) {
//根据返回值做判断
case MATCH_ROOT:
DBOpenHelper dbOpenHelper = new DBOpenHelper(getContext());
SQLiteDatabase db = dbOpenHelper.getWritableDatabase();
Cursor c = db.query("word", projection, selection, selectionArgs, null, null, sortOrder);
return c;
default:
throw new RuntimeException("非法的Uri -> " + uri);
}
}
@Override
public Uri insert(Uri uri, ContentValues values) {
// 当其它应用添加数据时回调
// 验证Uri
//第三步,与已经注册的URI进行匹配
int code = matcher.match(uri);
Log.d("teee", "uri -> " + uri.toString());
switch (code) {
//根据返回值做判断
case MATCH_ROOT:
Log.d("teee", "MATCH_ROOT");
DBOpenHelper dbOpenHelper = new DBOpenHelper(getContext());
SQLiteDatabase db = dbOpenHelper.getWritableDatabase();
long id = db.insert("word", null, values);
if (db.isOpen()) {
db.close();
db = null;
}
// content://cn.teee.providers.word/13
return ContentUris.withAppendedId(uri, id);
case MATCH_HELLO:
Log.d("teee", "MATCH_HELLO");
throw new RuntimeException("非法的Uri:" + uri);
case UriMatcher.NO_MATCH:
Log.d("teee", "NO_MATCH");
throw new RuntimeException("非法的Uri:" + uri);
}
return null;
}
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
// 当其它应用删除数据时回调
return 0;
}
@Override
public int update(Uri uri, ContentValues values, String selection,
String[] selectionArgs) {
// 当其它应用修改数据时回调
// -- 假设不提供修改数据的服务 --
throw new RuntimeException("不允许修改数据!!!");
}
@Override
public String getType(Uri uri) {
// (无视)
return null;
}
}