Android Content Provider 详解
2010-05-31 14:33:00 来源:WEB开发网}
@Override
public boolean onCreate() {
dbHelper = new DatabaseHelper(getContext());
return (dbHelper == null) ? false : true;
}
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
SQLiteDatabase db = dbHelper.getReadableDatabase();
qb.setTables(TABLE_NAME);
Cursor c = qb.query(db, projection, selection, null, null, null, sortOrder);
c.setNotificationUri(getContext().getContentResolver(), uri);
return c;
}
@Override
public int update(Uri uri, ContentValues contentvalues, String s, String[] as) {
return 0;
}
}
一个名为MyContentProvider的Content Provider创建完成了,它用于从Sqlite数据库中添加和读取记录。
Content Provider的入口需要在AndroidManifest.xml中配置:
< provider android:name=”MyContentProvider” android:authorities=”com.wissen.MyContentProvider” / >
之后,让我们来使用这个定义好的Content Provider:
package com.wissen.testApp;
public class MyContentDemo extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
insertRecord(”MyUser”);
displayRecords();
}
private void insertRecord(String userName) {
ContentValues values = new ContentValues();
values.put(MyUsers.User.USER_NAME, userName);
getContentResolver().insert(MyUsers.User.CONTENT_URI, values);
}
private void displayRecords() {
String columns[] = new String[] { MyUsers.User._ID, MyUsers.User.USER_NAME };
Uri myUri = MyUsers.User.CONTENT_URI;
Cursor cur = managedQuery(myUri, columns,null, null, null );
赞助商链接