转载:http://blog.csdn.net/bruse1990/article/details/19490343
(一)基本概念
1.ContentProvider为存储和获取数据提供了统一的接口
2.使用ContentProvider可以在不同的应用程序之间共享数据
1.每一个ContentProvider都拥有一个公共的URI,这个URI用于表示这个ContentProvider所提供的数据。
2.Android所提供的ContentProvider都存放在android.provider包当中。
1.query():查询
2.insert():插入
3.update():更新
4.delete():删除
5.getType():得到数据类型
6.onCreate():创建时的回调函数
1.定义一个CONTENT_URI常量
2.定义一个类,继承ContentProvider
3.实现query,insert,update,delete,getType和onCreate方法
4.在AndroidManifest.xml当中进行声明
(二)例子
- package com.example.contentprovider;
- import com.example.contentprovider.FirstProviderMetaData.UserTableMetaData;
- import android.content.Context;
- import android.database.sqlite.SQLiteDatabase;
- import android.database.sqlite.SQLiteOpenHelper;
- public class DBHelper extends SQLiteOpenHelper{
- public static final String DATABASE_NAME = "FirstProvider.db";
- public static final int DATABASE_VERSION = 1;
- public DBHelper(Context context) {
- super(context, DATABASE_NAME, null, DATABASE_VERSION);
- }
- @Override
- public void onCreate(SQLiteDatabase db) {
- System.out.println("create a Database");
- String sql = "create table " + UserTableMetaData.TABLE_NAME + "(" + UserTableMetaData._ID + " integer," + UserTableMetaData.USER_NAME + " varchar(20))";
- db.execSQL(sql);
- }
- @Override
- public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
- System.out.println("update a Database");
- }
- }
FirstProviderMetaData.java
- package com.example.contentprovider;
- import android.net.Uri;
- import android.provider.BaseColumns;
- public class FirstProviderMetaData {
- public static final String AUTHORIY = "com.example.contentprovider.FirstContentProvider";
- public static final class UserTableMetaData implements BaseColumns{
- public static final String TABLE_NAME = "users";
- public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORIY + "/users");
- public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.firstprovider.user";
- public static final String CONTENT_TYPE_ITEM = "vnd.android.cursor.item/vnd.firstprovider.user";
- public static final String USER_NAME = "name";
- public static final String DEFAULT_SORT_ORDER = "_id desc";
- }
- }
FirstContentProvider.java
- package com.example.contentprovider;
- import java.util.HashMap;
- import com.example.contentprovider.FirstProviderMetaData.UserTableMetaData;
- import android.content.ContentProvider;
- import android.content.ContentUris;
- import android.content.ContentValues;
- import android.content.UriMatcher;
- import android.database.Cursor;
- import android.database.SQLException;
- import android.database.sqlite.SQLiteDatabase;
- import android.database.sqlite.SQLiteQueryBuilder;
- import android.net.Uri;
- import android.text.TextUtils;
- public class FirstContentProvider extends ContentProvider{
- public static final UriMatcher uriMatcher;
- public static final int INCOMING_USER_COLLECTION = 1;
- public static final int INCOMING_USER_SINGLE = 2;
- private DBHelper dh;
- static{
- uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
- //把繁琐的地址变成一个标识符
- uriMatcher.addURI(FirstProviderMetaData.AUTHORIY, "users", INCOMING_USER_COLLECTION);
- uriMatcher.addURI(FirstProviderMetaData.AUTHORIY, "users/#", INCOMING_USER_SINGLE);
- }
- public static HashMap<String, String> userProjectMap;
- static{
- userProjectMap = new HashMap<String, String>();
- userProjectMap.put(UserTableMetaData._ID, UserTableMetaData._ID);
- userProjectMap.put(UserTableMetaData.USER_NAME, UserTableMetaData.USER_NAME);
- }
- @Override
- public int delete(Uri arg0, String arg1, String[] arg2) {
- return 0;
- }
- @Override
- public String getType(Uri uri) {
- System.out.println("getType");
- switch(uriMatcher.match(uri)){
- case INCOMING_USER_COLLECTION:
- return UserTableMetaData.CONTENT_TYPE;
- case INCOMING_USER_SINGLE:
- return UserTableMetaData.CONTENT_TYPE_ITEM;
- default:
- throw new IllegalArgumentException("Unknown URI" + uri);
- }
- }
- @Override
- public Uri insert(Uri uri, ContentValues values) {
- System.out.println("insert");
- SQLiteDatabase db = dh.getWritableDatabase();
- long rowId = db.insert(UserTableMetaData.TABLE_NAME, null, values);
- if(rowId > 0){
- Uri insertedUserUri = ContentUris.withAppendedId(UserTableMetaData.CONTENT_URI, rowId);
- getContext().getContentResolver().notifyChange(insertedUserUri, null);
- return insertedUserUri;
- }
- throw new SQLException("Failed to insert row into" + uri);
- }
- @Override
- public boolean onCreate() {
- dh = new DBHelper(getContext());
- System.out.println("onCreate");
- return false;
- }
- @Override
- public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
- String sortOrder) {
- SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
- switch(uriMatcher.match(uri)){
- case INCOMING_USER_COLLECTION:
- qb.setTables(UserTableMetaData.TABLE_NAME);
- qb.setProjectionMap(userProjectMap);
- break;
- case INCOMING_USER_SINGLE:
- qb.setTables(UserTableMetaData.TABLE_NAME);
- qb.setProjectionMap(userProjectMap);
- qb.appendWhere(UserTableMetaData._ID + "=" + uri.getPathSegments().get(1));
- break;
- }
- String orderBy;
- if(TextUtils.isEmpty(sortOrder)){
- orderBy = UserTableMetaData.DEFAULT_SORT_ORDER;
- }else{
- orderBy = sortOrder;
- }
- SQLiteDatabase db = dh.getWritableDatabase();
- Cursor c = qb.query(db, projection, selection, selectionArgs, null, null, sortOrder);
- c.setNotificationUri(getContext().getContentResolver(), uri);
- System.out.println("query");
- return c;
- }
- @Override
- public int update(Uri arg0, ContentValues arg1, String arg2, String[] arg3) {
- return 0;
- }
- }
MainActivity.java
- package com.example.contentprovider;
- import com.example.contentprovider.FirstProviderMetaData.UserTableMetaData;
- import android.net.Uri;
- import android.os.Bundle;
- import android.app.Activity;
- import android.content.ContentValues;
- import android.database.Cursor;
- import android.view.View;
- import android.view.View.OnClickListener;
- import android.widget.Button;
- public class MainActivity extends Activity {
- Button insertButton;
- Button queryButton;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- insertButton = (Button) findViewById(R.id.insertButton);
- queryButton = (Button) findViewById(R.id.queryButton);
- insertButton.setOnClickListener(new OnClickListener() {
- @Override
- public void onClick(View arg0) {
- ContentValues values = new ContentValues();
- values.put(UserTableMetaData.USER_NAME, "zhangsan");
- Uri uri = getContentResolver().insert(UserTableMetaData.CONTENT_URI, values);
- System.out.println("uri--->" + uri.toString());
- }
- });
- queryButton.setOnClickListener(new OnClickListener() {
- @Override
- public void onClick(View v) {
- Cursor c = getContentResolver().query(UserTableMetaData.CONTENT_URI, null, null, null, null);
- while(c.moveToNext()){
- System.out.println(c.getString(c.getColumnIndex(UserTableMetaData.USER_NAME)));
- }
- }
- });
- }
- }
manifest.xml
- <?xml version="1.0" encoding="utf-8"?>
- <manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="com.example.contentprovider"
- android:versionCode="1"
- android:versionName="1.0" >
- <uses-sdk
- android:minSdkVersion="10"
- android:targetSdkVersion="10" />
- <application
- android:allowBackup="true"
- android:icon="@drawable/ic_launcher"
- android:label="@string/app_name"
- android:theme="@style/AppTheme" >
- <activity
- android:name="com.example.contentprovider.MainActivity"
- android:label="@string/app_name" >
- <intent-filter>
- <action android:name="android.intent.action.MAIN" />
- <category android:name="android.intent.category.LAUNCHER" />
- </intent-filter>
- </activity>
- <provider
- android:name="com.example.contentprovider.FirstContentProvider"
- android:authorities="com.example.contentprovider.FirstContentProvider"/>
- </application>
- </manifest>
activity_main.xml
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:orientation="vertical">
- <Button
- android:id="@+id/insertButton"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="插入"/>
- <Button
- android:id="@+id/queryButton"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="查询"/>
- </LinearLayout>