当应用继承ContentProvider类,并重写该类用于提供数据和存储数据的方法,就可以向其他应用共享其数据。以前我们学习过文件的操作模式,通过指定文件的操作模式为Context.MODE_WORLD_READABLE 或Context.MODE_WORLD_WRITEABLE同样可以对外共享数据,但数据的访问方式会因数据存储的方式而不同,如:采用xml文件对外共享数据,需要进行xml解析来读写数据;采用sharedpreferences共享数据,需要使用sharedpreferences API读写数据。而使用ContentProvider共享数据的好处是统一了数据访问方式。
1.第一步需要继承ContentProvider并重写下面方法:
public class PersonContentProvider extends ContentProvider{
public boolean onCreate()
public Uri insert(Uri uri, ContentValues values)
public int delete(Uri uri, String selection, String[] selectionArgs)
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs)
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder)
public String getType(Uri uri)}
2. 第二步需要在AndroidManifest.xml使用<provider>对该ContentProvider进行配置,为了能让其他应用找到该ContentProvider , ContentProvider 采用了authorities(主机名/域名)对它进行唯一标识,你可以把 ContentProvider看作是一个网站(想想,网站也是提供数据者),authorities 就是他的域名:
<manifest .... >
<application android:icon="@drawable/icon" android:label="@string/app_name">
<provider android:name=".UserProvider" android:authorities="com.example.providerdemo.userProvider"/>
</application>
</manifest>
注意:一旦应用继承了ContentProvider类,后面我们就会把这个应用称为ContentProvider(内容提供者)。
ProviderDemo 拥有DB, 提供Provider,供外围进行增删改查。 (这里可以类比通讯录)
OneApp对他进行 操作
provider定义:
/** * */ package com.example.providerdemo; import android.content.ContentProvider; import android.content.ContentUris; import android.content.ContentValues; import android.content.UriMatcher; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.net.Uri; /** * * @author baoxing.gbx * @version $Id: UserProvider.java, v 0.1 2015年8月21日 上午10:25:48 baoxing.gbx Exp $ */ public class UserProvider extends ContentProvider{ private DBopenHelper dbOpenHelper; private static final UriMatcher MATCHER = new UriMatcher(UriMatcher.NO_MATCH); private static final int UserOne = 1; private static final int UserList = 2; static{ MATCHER.addURI("com.example.providerdemo.userProvider", "user", UserList); MATCHER.addURI("com.example.providerdemo.userProvider", "user/#", UserOne); } @Override public boolean onCreate() { dbOpenHelper = new DBopenHelper(this.getContext()); return true; } @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { SQLiteDatabase db = dbOpenHelper.getWritableDatabase(); switch (MATCHER.match(uri)) { case UserOne: long key = ContentUris.parseId(uri); String where = "id = "+ key; if(selection!=null && !"".equals(selection.trim())){ where += " and "+ selection; } Cursor cursor = db.query("user", null, where, selectionArgs, null, null, null, null); return cursor; case UserList: cursor = db.query("user", null, null, selectionArgs, null, null, null, null); return cursor; default: throw new IllegalArgumentException("this is Unknown Uri:"+ uri); } } @Override public String getType(Uri uri) { // TODO Auto-generated method stub return null; } @Override public Uri insert(Uri uri, ContentValues values) { SQLiteDatabase db = dbOpenHelper.getWritableDatabase(); switch (MATCHER.match(uri)) { case UserOne: long rowid = db.insert("user", "", values);//主键值 Uri insertUri = ContentUris.withAppendedId(uri, rowid); this.getContext().getContentResolver().notifyChange(uri, null);//发出数据变化通知 return insertUri; default: throw new IllegalArgumentException("this is Unknown Uri:"+ uri); } } @Override public int delete(Uri uri, String selection, String[] selectionArgs) { SQLiteDatabase db = dbOpenHelper.getWritableDatabase(); int nnum = 0; switch (MATCHER.match(uri)) { case UserOne: long key = ContentUris.parseId(uri); String where = "id = " + key; if (null != selection && !"".equals(selection)) { where += "and " + selection; } nnum = db.delete("user", where, selectionArgs); return nnum; case UserList: nnum = db.delete("user", selection, selectionArgs); return nnum; default: throw new IllegalArgumentException("this is Unknown Uri:"+ uri); } } @Override public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { SQLiteDatabase db = dbOpenHelper.getWritableDatabase(); int nnum = 0 ; switch (MATCHER.match(uri)) { case UserOne: long key = ContentUris.parseId(uri); String where = "id = " + key; if (null != selection && !"".equals(selection)) { where += "and " + selection; } nnum = db.update("user", values, where, selectionArgs); return nnum; case UserList: nnum = db.update("user", values, selection, selectionArgs); return nnum; default: throw new IllegalArgumentException("this is Unknown Uri:"+ uri); } } }
DB操作:
package com.example.providerdemo; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteDatabase.CursorFactory; import android.database.sqlite.SQLiteOpenHelper; import android.nfc.Tag; import android.os.Build.VERSION; import android.util.Log; /** * * @author baoxing.gbx * @version $Id: DBopenHelper.java, v 0.1 2015年7月11日 下午9:39:03 baoxing.gbx Exp $ */ public class DBopenHelper extends SQLiteOpenHelper{ /** 数据库名称 */ private static final String DB_NAME = "test.db"; private static final int VERSION = 1; private static final String Tag = "DBopenHelper"; // 初始化数据库开启装置 public DBopenHelper(Context context) { super(context, DB_NAME, null, VERSION); // TODO Auto-generated constructor stub } // @Override public void onCreate(SQLiteDatabase db) { Log.i(Tag, "onCreate 被调用"); db.execSQL("create table user (id integer primary key autoincrement, name varchar(20),sex varchar(20), age integer )"); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { Log.i(Tag, "onUpgrade 被调用"); db.execSQL("DROP TABLE IF EXISTS person"); onCreate(db); } }
OneApp测试
/** * */ package com.demo.oneapp.test; import java.util.Date; import android.R.integer; import android.content.ContentResolver; import android.content.ContentValues; import android.database.Cursor; import android.net.Uri; import android.test.AndroidTestCase; import android.util.Log; /** * * @author baoxing.gbx * @version $Id: TestProvider.java, v 0.1 2015年8月20日 下午8:50:13 baoxing.gbx Exp $ */ public class TestProvider extends AndroidTestCase { public void testAdd() { Uri uri = Uri.parse("content://com.example.providerdemo.userProvider/user"); ContentResolver resolver = this.getContext().getContentResolver(); for (int i = 0; i < 10; ++i) { ContentValues values = new ContentValues(); values.put("name", "muyou" + i); values.put("sex", "男"); values.put("age", 18 + i); Uri uri2 = resolver.insert(uri, values); System.out.println("完成:" + uri2); } } public void testDel() { // 查询单个 Uri uri = Uri.parse("content://com.example.providerdemo.userProvider/user/2"); ContentResolver resolver = this.getContext().getContentResolver(); Cursor cursor = resolver.query(uri, null, null, null, null); while (cursor.moveToNext()) { int id = cursor.getInt(cursor.getColumnIndex("id")); String name = cursor.getString(cursor.getColumnIndex("name")); String sex = cursor.getString(cursor.getColumnIndex("sex")); int age = cursor.getInt(cursor.getColumnIndex("age")); Log.i("testQuery", "id="+ id + "name=" + name + "sex=" + sex + "age=" + age); } uri = Uri.parse("content://com.example.providerdemo.userProvider/user/2"); resolver = this.getContext().getContentResolver(); resolver.delete(uri, null, null); // 查询单个 uri = Uri.parse("content://com.example.providerdemo.userProvider/user/2"); resolver = this.getContext().getContentResolver(); cursor = resolver.query(uri, null, null, null, null); while (cursor.moveToNext()) { int id = cursor.getInt(cursor.getColumnIndex("id")); String name = cursor.getString(cursor.getColumnIndex("name")); String sex = cursor.getString(cursor.getColumnIndex("sex")); int age = cursor.getInt(cursor.getColumnIndex("age")); Log.i("testQuery", "id="+ id + "name=" + name + "sex=" + sex + "age=" + age); } } public void testUpdate() { // 查询单个 Uri uri = Uri.parse("content://com.example.providerdemo.userProvider/user/3"); ContentResolver resolver = this.getContext().getContentResolver(); Cursor cursor = resolver.query(uri, null, null, null, null); while (cursor.moveToNext()) { int id = cursor.getInt(cursor.getColumnIndex("id")); String name = cursor.getString(cursor.getColumnIndex("name")); String sex = cursor.getString(cursor.getColumnIndex("sex")); int age = cursor.getInt(cursor.getColumnIndex("age")); Log.i("testQuery", "id="+ id + "name=" + name + "sex=" + sex + "age=" + age); } uri = Uri.parse("content://com.example.providerdemo.userProvider/user/3"); resolver = this.getContext().getContentResolver(); ContentValues values = new ContentValues(); values.put("name", "cool"); resolver.update(uri, values, null, null); // 查询单个 uri = Uri.parse("content://com.example.providerdemo.userProvider/user/3"); resolver = this.getContext().getContentResolver(); cursor = resolver.query(uri, null, null, null, null); while (cursor.moveToNext()) { int id = cursor.getInt(cursor.getColumnIndex("id")); String name = cursor.getString(cursor.getColumnIndex("name")); String sex = cursor.getString(cursor.getColumnIndex("sex")); int age = cursor.getInt(cursor.getColumnIndex("age")); Log.i("testQuery", "id="+ id + "name=" + name + "sex=" + sex + "age=" + age); } } public void testQuery() { // 查询所有 Uri uri = Uri.parse("content://com.example.providerdemo.userProvider/user"); ContentResolver resolver = this.getContext().getContentResolver(); Cursor cursor = resolver.query(uri, null, null, null, null); while (cursor.moveToNext()) { int id = cursor.getInt(cursor.getColumnIndex("id")); String name = cursor.getString(cursor.getColumnIndex("name")); String sex = cursor.getString(cursor.getColumnIndex("sex")); int age = cursor.getInt(cursor.getColumnIndex("age")); Log.i("testQuery", "id="+ id + "name=" + name + "sex=" + sex + "age=" + age); } // 查询单个 uri = Uri.parse("content://com.example.providerdemo.userProvider/user/5"); resolver = this.getContext().getContentResolver(); cursor = resolver.query(uri, null, null, null, null); while (cursor.moveToNext()) { int id = cursor.getInt(cursor.getColumnIndex("id")); String name = cursor.getString(cursor.getColumnIndex("name")); String sex = cursor.getString(cursor.getColumnIndex("sex")); int age = cursor.getInt(cursor.getColumnIndex("age")); Log.i("testQuery", "id="+ id + "name=" + name + "sex=" + sex + "age=" + age); } } }