Android 数据存储之 ContentProvider
2010-03-03 16:44:00 来源:WEB开发网import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
public class ContactContentProvider extends ContentProvider {
// 通过UriMatcher匹配外部请求
private static UriMatcher uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
// 通过openHelper进行数据库读写
private MyOpenHelper openHelper;
// 匹配状态常量
private static final int CONTACT_LIST = 1;
private static final int CONTACT = 2;
// 表名
private static final String tableName = "contacts";
// 添加Uri
static {
uriMatcher.addURI("com.changcheng.sqlite.provider", "contact",
CONTACT_LIST);
uriMatcher.addURI("com.changcheng.sqlite.provider", "contact/#",
CONTACT);
}
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
SQLiteDatabase db = this.openHelper.getWritableDatabase();
int result;
switch (uriMatcher.match(uri)) {
case CONTACT_LIST:
result = db.delete(tableName, selection, selectionArgs);
break;
case CONTACT:
long id = ContentUris.parseId(uri);
String where = "_id=" + id;
if (selection != null && !"".equals(selection)) {
where = where + " and " + selection;
}
result = db.delete(tableName, where, selectionArgs);
break;
default:
throw new IllegalArgumentException("Uri IllegalArgument:" + uri);
}
return result;
}
@Override
public String getType(Uri uri) {
switch (uriMatcher.match(uri)) {
case CONTACT_LIST:// 集合类型必须在前面加上vnd.android.cursor.dir/
return "vnd.android.cursor.dir/contactlist";
更多精彩
赞助商链接