Android存储-ContentProvider

ContentProvider的优势是写个接口供它人增删改查等操作,其它人不用知道他是XML文件还是图片还是txt,只需要用就可以了。

并且ContentProvider还可以监听数据的变化。


ContentProvider类

public class PersonProvider extends ContentProvider {

	private SQLiteOpenHelper sqlite;
	// 不匹配返回-1
	private static final UriMatcher MATCHER = new UriMatcher(
			UriMatcher.NO_MATCH);
	private static final int PERSONS = 1;
	private static final int PERSON = 2;
	static {
		//一定要和配置文件中的一致
		MATCHER.addURI("cn.decamincow.provider.personprovider", "person",
				PERSONS);
		MATCHER.addURI("cn.decamincow.provider.personprovider", "person/#",
				PERSON);
	}

	// 创建实力的时候被调用,初始化可在此做
	@Override
	public boolean onCreate() {
		// 参数分别为:activity,库名,游标的引用,版本号
		sqlite = new SQLiteOpenHelper(this.getContext(), "test", null, 1) {

			// 版本号改变调用此方法
			@Override
			public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {
				// TODO Auto-generated method stub
			}

			// 第一次创建数据库的时候调用,创建了一个person表
			@Override
			public void onCreate(SQLiteDatabase sqlite) {

				// 判断是否有该表
				// 创建表
				sqlite.execSQL("CREATE TABLE IF NOT EXISTS person (_id INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR, age SMALLINT)");
			}
		};
		return false;
	}

	@Override
	public int delete(Uri arg0, String arg1, String[] arg2) {

		SQLiteDatabase db = sqlite.getWritableDatabase();
		int num = 0;
		switch (MATCHER.match(arg0)) {
		case 1:
			//
			num = db.delete("person", arg1, arg2);
			break;
		case 2:
			long rowid = ContentUris.parseId(arg0);
			String where = "_id=" + rowid;
			if (arg1 != null && "".equals(arg1.trim())) {
				where = where + " and " + arg1;
			}
			num = db.delete("person", where, arg2);
			break;
		default:
			throw new IllegalAccessError("Uri Not Found");
		}
		return num;
	}

	@Override
	public String getType(Uri arg0) {
		switch (MATCHER.match(arg0)) {
		case 1:
			return "vnd.android.cursor.dir/person";
		case 2:
			return "vnd.android.cursor.item/person";
		default:
			throw new IllegalAccessError("Uri Not Found");
		}
	}

	@Override
	public Uri insert(Uri arg0, ContentValues arg1) {

		SQLiteDatabase db = sqlite.getWritableDatabase();
		switch (MATCHER.match(arg0)) {
		case 1:
			long rowId = db.insert("person", "", arg1);
			Uri uri = ContentUris.withAppendedId(arg0, rowId);
			//监听插入
			this.getContext().getContentResolver().notifyChange(uri, null);
			return uri;

		default:
			throw new IllegalAccessError("Uri Not Found");
		}
	}

/*	参数:分别表示
	uri,
	所展示的列String[] arg1 = {"name", "age"},
	条件筛选String arg2 = "name" + "=?",
	查询条件参数String[] arg3 = {"guoren"},
	排序 arg4 = "id asc"*/
	
	@Override
	public Cursor query(Uri arg0, String[] arg1, String arg2, String[] arg3,
			String arg4) {
		
		SQLiteDatabase db = sqlite.getWritableDatabase();
		switch (MATCHER.match(arg0)) {
		case 1:
			//
			return db.query("person", arg1, arg2, arg3, null, null, arg4);
		case 2:
			long rowid = ContentUris.parseId(arg0);
			String where = "_id=" + rowid;
			if (arg2 != null && "".equals(arg2.trim())) {
				where = where + " and " + arg2;
			}
			return db.query("person", arg1, arg2, arg3, null, null, arg4);
		default:
			throw new IllegalAccessError("Uri Not Found");
		}
	}

	@Override
	public int update(Uri arg0, ContentValues arg1, String arg2, String[] arg3) {
		SQLiteDatabase db = sqlite.getWritableDatabase();
		int num = 0;
		switch (MATCHER.match(arg0)) {
		case 1:
			//
			num = db.update("person", arg1, arg2, arg3);
			break;
		case 2:
			long rowid = ContentUris.parseId(arg0);
			String where = "_id=" + rowid;
			if (arg2 != null && "".equals(arg2.trim())) {
				where = where + " and " + arg2;
			}
			num = db.update("person", arg1, where, arg3);
			break;
		default:
			throw new IllegalAccessError("Uri Not Found");
		}
		return num;
	}

}


别忘了加

    <application
       ... >
        <provider android:name=".PersonProvider" android:authorities="cn.decamincow.provider.personprovider"/>
              ...
    </application>


测试类

public class AccessContentProvider extends AndroidTestCase {
	
	public void insertTest() throws Exception{
		
		Uri uri = Uri.parse("content://cn.decamincow.provider.personprovider/person");
		ContentResolver contentResolver = this.getContext().getContentResolver();
		ContentValues contentValues = new ContentValues();
		contentValues.put("name", "guoren8");
		contentValues.put("age", "888");
		contentResolver.insert(uri, contentValues);
		
	}
	
	public void delTest() throws Exception{
		
		Uri uri = Uri.parse("content://cn.decamincow.provider.personprovider/person/2");
		ContentResolver contentResolver = this.getContext().getContentResolver();
		contentResolver.delete(uri, null, null);
		
	}
	
	public void updateTest() throws Exception{
		
		Uri uri = Uri.parse("content://cn.decamincow.provider.personprovider/person/3");
		ContentResolver contentResolver = this.getContext().getContentResolver();
		ContentValues contentValues = new ContentValues();
		contentValues.put("name", "guoren");
		contentResolver.update(uri, contentValues, null, null);
		
	}

	@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
	public void searchTest() throws Exception{
		
		Uri uri = Uri.parse("content://cn.decamincow.provider.personprovider/person");
		ContentResolver contentResolver = this.getContext().getContentResolver();
		Cursor cursor = contentResolver.query(uri, null, null, null, null, null);
		while(cursor.moveToNext()){
			
			String age = cursor.getString(cursor.getColumnIndex("age"));
			Log.i("age", age);
		}
		cursor.close();
	}
	
}


监听数据变化的Activity

public class MainActivity extends ActionBarActivity{

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		Uri uri = Uri.parse("content://cn.decamincow.provider.personprovider/person");
		this.getContentResolver().registerContentObserver(uri, true, new PersonContentObserver(new Handler()));
	}
	
	private class PersonContentObserver extends ContentObserver{
		public PersonContentObserver(Handler handler){
			super(handler);
			
		}

		@Override
		public void onChange(boolean selfChange) {
			
			Uri uri = Uri.parse("content://cn.decamincow.provider.personprovider/person");
			Cursor cursor = getContentResolver().query(uri, null, null, null, null);
			while(cursor.moveToNext()){
				
				String age = cursor.getString(cursor.getColumnIndex("age"));
				Log.i("age", age);
			}
			cursor.close();
		}
	}

}


监听的时候别忘了配制

 </application>

    <instrumentation
        android:name="android.test.InstrumentationTestRunner"
        android:label="test"
        android:targetPackage="com.example.andsave4contentprovider" />


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值