国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

自定義ContentProvider

2019-11-09 14:33:32
字體:
來源:轉載
供稿:網友

自定義ContentPRovider

AndroidManifest.xml

在manifest節點下添加兩個permission,作為讀取和修改的權限。
<!-- 定義讀取權限 --><permission android:name="com.blog.demo.READ_PEOPLE" /><!-- 定義修改權限 --><permission android:name="com.blog.demo.WRITE_PEOPLE" />在application界面下添加provider節點
<!-- com.blog.demo.content作為標識 --><!-- 內容在PeopleContentProvider中實現 --><!-- 設置讀寫權限 --><!-- 設置export為true,對其他apk開放  --><provider	android:authorities="com.blog.demo.content"	android:name=".PeopleContentProvider"	android:readPermission="com.blog.demo.READ_PEOPLE"	android:writePermission="com.blog.demo.WRITE_PEOPLE"	android:exported="true" />

PeopleContentProvider

PeopleContentProvider繼承了ContentProvider,實現了各種操作的接口。首先需要定義我們自己的UriMatcher來解析傳遞過來的uri,分別定義了“people”和“people/#”兩種,在查詢時會進行區分。
private static final int PEOPLE      = 1;private static final int PEOPLE_ID   = 2;private static final UriMatcher uriMatcher;static {	uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);	uriMatcher.addURI(AUTHORITY, "people", PEOPLE);	uriMatcher.addURI(AUTHORITY, "people/#", PEOPLE_ID);}@Nullable@Overridepublic String getType(Uri uri) {	switch(uriMatcher.match(uri)) {		case PEOPLE: // 集合類型 vnd.android.cursor.dir			return "vnd.android.cursor.dir/com.blog.demo.people";		case PEOPLE_ID: // 非集合類型 vnd.android.cursor.item			return "vnd.android.cursor.item/com.blog.demo.people";		default:			throw new IllegalArgumentException("Unsupported URI: " + uri);	}}其次我們需要創建一個數據庫,在onCreate里面創建。
private PeopleSQLiteOpenHelper helper;@Overridepublic boolean onCreate() {	helper = new PeopleSQLiteOpenHelper(getContext());	return true;}

public class PeopleSQLiteOpenHelper extends SQLiteOpenHelper {    public final static String LOGTAG = "PeopleSQLiteOpenHelper";    public final static String DB_NAME = "people.db";    public final static String TABLE_NAME = "people";    public final static int VERSION = 1;    public final static String COL_ID   = "_id";    public final static String COL_NAME = "name";    public final static String COL_ADDR = "addr";    public final static String COL_AGE  = "age";    public final static String TABLE_CREATE = 			"create table if not exists " + TABLE_NAME + "("            + COL_ID + " integer primary key autoincrement not null,"            + COL_NAME + " text not null, "            + COL_ADDR + " text not null, "            + COL_AGE + " integer "            + ")";    public PeopleSQLiteOpenHelper(Context context) {        this(context, DB_NAME, null, VERSION);    }    public PeopleSQLiteOpenHelper(Context context, String name,			SQLiteDatabase.CursorFactory factory, int version) {        super(context, name, factory, version);        LogUtil.log(LOGTAG, "name = " + name + " version = " + version);    }    @Override    public void onCreate(SQLiteDatabase db) {        LogUtil.log(LOGTAG, "onCreate");        db.execSQL(TABLE_CREATE);    }    @Override    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {        LogUtil.log(LOGTAG, "onUpgrade");    }}

最后實現各種操作方法
@Nullable@Overridepublic Cursor query(Uri uri, String[] projection, String selection,		String[] selectionArgs, String sortOrder) {	LogUtil.log(LOGTAG, "query");	if (uriMatcher.match(uri) == PEOPLE) {		// 查詢所有people數據		return helper.getReadableDatabase().query(TABLE_NAME, projection,				selection, selectionArgs, null, null, sortOrder);	} else if (uriMatcher.match(uri) == PEOPLE_ID) {		// 查詢所有指定id的people數據		String id = uri.getPathSegments().get(1);		return helper.getReadableDatabase().query(TABLE_NAME, projection, 				PeopleSQLiteOpenHelper.COL_ID +"=?", new String[]{id},				null, null, sortOrder);	}	return null;}@Nullable@Overridepublic Uri insert(Uri uri, ContentValues values) {	if (uriMatcher.match(uri) == PEOPLE) {		long rowid = helper.getWritableDatabase().insert(TABLE_NAME, null, values);		if (rowid > 0) {			Uri rowUri = ContentUris.withAppendedId(uri, rowid);			getContext().getContentResolver().notifyChange(rowUri, null);			return rowUri;		}		throw new SQLException("Failed to insert row into " + uri);	}	throw new IllegalArgumentException("Unsupported URI: " + uri);}@Overridepublic int delete(Uri uri, String selection, String[] selectionArgs) {	if (uriMatcher.match(uri) == PEOPLE) {		return helper.getWritableDatabase().delete(TABLE_NAME, 				selection, selectionArgs);	} else if (uriMatcher.match(uri) == PEOPLE_ID) {		String id = uri.getPathSegments().get(1);		return helper.getWritableDatabase().delete(TABLE_NAME,				PeopleSQLiteOpenHelper.COL_ID +"=?", new String[]{id});	}	throw new IllegalArgumentException("Unsupported URI: " + uri);}@Overridepublic int update(Uri uri, ContentValues values, String selection,			String[] selectionArgs) {	if (uriMatcher.match(uri) == PEOPLE) {		return helper.getWritableDatabase().update(TABLE_NAME, values,				selection, selectionArgs);	} else if (uriMatcher.match(uri) == PEOPLE_ID) {		String id = uri.getPathSegments().get(1);		return helper.getWritableDatabase().update(TABLE_NAME, values,				PeopleSQLiteOpenHelper.COL_ID +"=?", new String[]{id});	}	throw new IllegalArgumentException("Unsupported URI: " + uri);}

讀取自定義ContentProvider

在AndroidManifest.xml文件中,添加權限。
<uses-permission android:name="com.blog.demo.READ_PEOPLE"/><uses-permission android:name="com.blog.demo.WRITE_PEOPLE"/>使用getContentResolver來操作數據
// 查詢數據private List<People> query() {	List<People> list = new ArrayList<People>();	Cursor cursor = getContentResolver().query(Content.People.CONTENT_URI,			null, null, null, null);	if (cursor != null) {		while (cursor.moveToNext()) {			int id = cursor.getInt(cursor.getColumnIndex(PeopleColumns.ID));			String name = cursor.getString(cursor.getColumnIndex(PeopleColumns.NAME));			String addr = cursor.getString(cursor.getColumnIndex(PeopleColumns.ADDR));			int age = cursor.getInt(cursor.getColumnIndex(PeopleColumns.AGE));			list.add(new People(id, name, addr, age));		}		cursor.close();	}	return list;}// 查詢數據private People query(int id) {	Cursor cursor = getContentResolver().query(		ContentUris.withAppendedId(Content.People.CONTENT_URI, id),		null, null, null, null);	People people = null;	if (cursor != null) {		if (cursor.moveToNext()) {			int rid = cursor.getInt(cursor.getColumnIndex(PeopleColumns.ID));			String name = cursor.getString(cursor.getColumnIndex(PeopleColumns.NAME));			String addr = cursor.getString(cursor.getColumnIndex(PeopleColumns.ADDR));			int age = cursor.getInt(cursor.getColumnIndex(PeopleColumns.AGE));			people = new People(rid, name, addr, age);		}		cursor.close();	}	return people;}// 插入數據private void insert(String name, String addr, String age) {	ContentValues insertValues = new ContentValues();	insertValues.put(PeopleColumns.NAME, name);	insertValues.put(PeopleColumns.ADDR, addr);	insertValues.put(PeopleColumns.AGE, age);	getContentResolver().insert(Content.People.CONTENT_URI, insertValues);}// 修改數據private void update(int id, String name, String addr, String age) {	ContentValues updateValues = new ContentValues();	updateValues.put(PeopleColumns.NAME, name);	updateValues.put(PeopleColumns.ADDR, addr);	updateValues.put(PeopleColumns.AGE, age);	getContentResolver().update(ContentUris.withAppendedId(			Content.People.CONTENT_URI, id),			updateValues, null, null);}// 刪除數據private void delete(int id) {	getContentResolver().delete(ContentUris.withAppendedId(			Content.People.CONTENT_URI, id), null, null);}也可以用其他方式去修改和刪除數據
// 修改數據private void update(int id, String name, String addr, String age) {	ContentValues updateValues = new ContentValues();	updateValues.put(PeopleColumns.NAME, name);	updateValues.put(PeopleColumns.ADDR, addr);	updateValues.put(PeopleColumns.AGE, age);	getContentResolver().update(Content.People.CONTENT_URI, updateValues, 			PeopleColumns.ID + "=?",			new String[] { Integer.toString(id) });}// 刪除數據private void delete(int id) {	getContentResolver().delete(Content.People.CONTENT_URI, 			PeopleColumns.ID + "=?", new String[] {Integer.toString(id)});}輔助類Content
public class Content {	public final static class People {		public final static Uri CONTENT_URI = 				Uri.parse("content://com.blog.demo.content/people");				public final static class PeopleColumns {			public final static String ID 	= "_id";			public final static String NAME = "name";			public final static String ADDR = "addr";			public final static String AGE 	= "age";		}			}}
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 雷波县| 赤壁市| 澄迈县| 洛南县| 那坡县| 海宁市| 山阴县| 江川县| 开原市| 罗田县| 基隆市| 永安市| 枣阳市| 荔浦县| 泽州县| 庆阳市| 潞西市| 西青区| 永嘉县| 义马市| 南宁市| 嘉鱼县| 宁武县| 乐至县| 汨罗市| 城市| 白玉县| 虞城县| 吴堡县| 保德县| 永和县| 余江县| 攀枝花市| 张家港市| 思南县| 苏尼特左旗| 定日县| 汶上县| 葵青区| 洛宁县| 榕江县|