Android ContentProvider+ContentObserver

说明:文章仅供本人学习记录所用。

1.理解含义:

ContentProvider: 内容提供者,将数据以表的形式进行操作。主要实现应用程序间数据共享,操作系统本地数据(包括短       信、音频、视屏、数据库)。

ContentObserver:内容观察者,监听数据变化。

2.使用方法:

ContentProvider:

1)步骤:新建MyProvider类继承ContentProvider类;注册URI;重写方法(onCreate、query、bulkInsert、insert、           delete、update);在AndroidManifest.xml中配置provider;

2)代码:

public class MyProvider extends ContentProvider {
	private static UriMatcher matcher = new UriMatcher(UriMatcher.NO_MATCH);
	private static final int INSERT = 1;
	private static final int UPDATE = 2;
	private static final int DELETE = 3;
	private static final int QUERY = 4;
	private static final int INSERTS = 5;
	private DBHelper dbOpenHelper;
	private String TAG = "Provider";
	static {
		// 为UriMatcher注册si四个Uri
		matcher.addURI(Picture.AUTHORITY, "insert", INSERT);
		matcher.addURI(Picture.AUTHORITY, "update", UPDATE);
		matcher.addURI(Picture.AUTHORITY, "delete", DELETE);
		matcher.addURI(Picture.AUTHORITY, "query", QUERY);
		matcher.addURI(Picture.AUTHORITY, "inserts", INSERTS);
		//说明Picture.AUTHORITY:表示你要操作的ContentProvider,一般以要操作的实体类的包名命名。
	}

	@Override
	public boolean onCreate() {
	        //获取数据库辅助类
		dbOpenHelper = DBHelper.getInstance(getContext());
		DatabaseManager.initializeInstance(dbOpenHelper);
		return true;
	}

	@Override
	public Cursor query(Uri uri, String[] projection, String selection,
			String[] selectionArgs, String sortOrder) {
		// TODO Auto-generated method stub
		int code = matcher.match(uri);
		Cursor c = null;
		switch (code) {
		case QUERY:
			SQLiteDatabase database = dbOpenHelper.getReadableDatabase();
			c = database.query("picture", projection, selection, selectionArgs,
					null, null, sortOrder);

			c.setNotificationUri(getContext().getContentResolver(), uri);
			DatabaseManager.getInstance().closeDatabase();
		case UriMatcher.NO_MATCH:
			Log.i(TAG, "------------未知的URI" + uri);
			break;
		}
		return c;
	}

	@Override
	public String getType(Uri uri) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Uri insert(Uri uri, ContentValues values) {
		int code = matcher.match(uri);
		switch (code) {
		case INSERT:
			SQLiteDatabase database = DatabaseManager.getInstance()
					.openDatabase();// 线程安全并发操作数据库
			try {// 获得数据库实例
				database.insert("picture", null, values);
				getContext().getContentResolver().notifyChange(uri, null);
			} catch (Exception ex) {
				Log.i(TAG, "insert ex=====" + ex.toString());
			} finally {
				DatabaseManager.getInstance().closeDatabase();
			}
			break;
		case UriMatcher.NO_MATCH:
			Log.i(TAG, "------------未知的URI" + uri);
			break;
		}

		return null;
	}
	/**
	 * 批量插入
	 */
	@Override
	public int bulkInsert(Uri uri, ContentValues[] values) {
		int code = matcher.match(uri);
		switch (code) {
		case INSERTS:
			SQLiteDatabase database = DatabaseManager.getInstance()
					.openDatabase();// 线程安全并发操作数据库
			try {// 获得数据库实例
				int numValues = 0;
				numValues = values.length;
				for (int i = 0; i < numValues; i++) {
					ContentValues value = values[i];
					database.delete("picture", "name = ?",
							new String[] { String.valueOf(value.get("name")) });
					Log.i(TAG,
							"name===== values"
									+ String.valueOf(value.get("name")));
					database.insert("picture", null, values[i]);
					Log.i(TAG, "Value insert====" + i);
				}
				getContext().getContentResolver().notifyChange(uri, null);
			} catch (Exception ex) {
				Log.i(TAG, "insert ex=====" + ex.toString());
			} finally {
				DatabaseManager.getInstance().closeDatabase();
			}
			break;
		case UriMatcher.NO_MATCH:
			Log.i(TAG, "------------未知的URI" + uri);
			break;
		}

		return 0;

	}

	@Override
	public int delete(Uri uri, String selection, String[] selectionArgs) {
		int code = matcher.match(uri);
		switch (code) {
		case DELETE:
			SQLiteDatabase database = DatabaseManager.getInstance()
					.openDatabase();
			int i = 0;
			try {
				i = database.delete("picture", selection, selectionArgs);
				if (i > 0) {
					getContext().getContentResolver().notifyChange(uri, null);
				}
			} catch (Exception ex) {
				Log.i(TAG, "delete ex====" + ex.toString());
			} finally {
				// database.close();
				DatabaseManager.getInstance().closeDatabase();
			}

			return i;
		case UriMatcher.NO_MATCH:
			Log.i(TAG, "------------未知的URI" + uri);
			break;
		}
		return 0;
	}

	@Override
	public int update(Uri uri, ContentValues values, String selection,
			String[] selectionArgs) {
		// TODO Auto-generated method stub
		int code = matcher.match(uri);
		switch (code) {
		case UPDATE:
			// SQLiteDatabase database = dbOpenHelper.getReadableDatabase();
			SQLiteDatabase database = DatabaseManager.getInstance()
					.openDatabase();
			int i = 0;
			try {
				i = database
						.update("picture", values, selection, selectionArgs);
				if (i != 0) {
					getContext().getContentResolver().notifyChange(uri, null);
				}
			} catch (Exception ex) {
				Log.i(TAG, "update ex===" + ex.toString());
			} finally {
				// database.close();
				DatabaseManager.getInstance().closeDatabase();
			}
			return i;
		case UriMatcher.NO_MATCH:
			Log.i(TAG, "------------未知的URI" + uri);
			break;
		}
		return 0;
	}

}

//在数据库操作类中添加以下方法。
//单条数据添加
public static void addPicture(Picture picture) {
		Uri uri = Uri.parse("content://" + Picture.AUTHORITY + "/insert");
		ContentValues values = new ContentValues();//封装数据
		values.put("name", picture.name);
		...
		AppApplication.getInstance().getContentResolver().insert(uri, values);
	}
//多条数据添加
public static void addPictures(List<Picture> pictures) {
		Uri uri = Uri.parse("content://" + Picture.AUTHORITY + "/inserts");
		ContentValues[] values = new ContentValues[pictures.size()];
		for (int i = 0; i < pictures.size(); i++) {
			Picture picture = pictures.get(i);
			ContentValues value = new ContentValues();
			value.put("name", picture.name);
			...
			values[i] = value;
		}
		Log.i(TAG, "addPictures_values_size=====" + values.length);
		AppApplication.getInstance().getContentResolver().bulkInsert(uri, values);
	}
//删除操作
public static void deletePictureTag() {
		Uri uri = Uri.parse("content://" + Picture.AUTHORITY + "/delete");
		int i = AppApplication.getInstance().getContentResolver()
				.delete(uri, "whereName = ?", new String[] { "value" });
	}	

//修改操作
public static void updatePicture(Picture picture) {
		Uri uri = Uri.parse("content://" + Picture.AUTHORITY + "/update");
		ContentValues values = new ContentValues();
		values.put("tagStatus", picture.tagStatus);
		int i = AppApplication.getInstance().getContentResolver()
				.update(uri, values, "whereName = ?", new String[] { picture.name });
	}
//AndroidManifest.xml中配置provider
<provider
            android:name="com....provider.MyProvider"//包名
            android:authorities="com....provider.myProvide" />

ContentObserver:

1)步骤:注册与注销ContentObserver;添加ContentObserver方法。

2)代码:

//uri与provider中注册的uri对应
Uri uri = Uri.parse("content://" + Picture.AUTHORITY + "/insert");//监听添加
getContentResolver().registerContentObserver(uri, true, cob);
Uri uri_inserts = Uri.parse("content://" + Picture.AUTHORITY+ "/inserts");//监听批量添加
getContentResolver().registerContentObserver(uri_inserts, true, cob);
Uri uri_update = Uri.parse("content://" + Picture.AUTHORITY + "/update");//监听修改
getContentResolver().registerContentObserver(uri_update, true, cob);

getContentResolver().unregisterContentObserver(cob);//在onDestroy销毁

//监听数据改变的方法
private ContentObserver cob = new ContentObserver(new Handler()) {
		@Override
		public boolean deliverSelfNotifications() {
			return super.deliverSelfNotifications();
		}

		@Override
		public void onChange(boolean selfChange) {
			super.onChange(selfChange);
			//改变数据时做出相应的操作
			......
			}
}
时间: 2024-08-03 16:18:47

Android ContentProvider+ContentObserver的相关文章

android,ContentProvider+ContentObserver+ContentResolver,用法。

这个是传智播客老师讲android开发时的一个图. 一. PersonProvider继承ContentProvider,实现ContentProvider中的数据操作类. 在需要监听的操作中添加添加数据变化通知. this.getContext().getContentResolver().notifyChange(uri, null); 第二个参数,数据变化的监听者,可以不设置,也即是设为null,如果给定了这个监听者,不管外面有多少个应用要设置监听,进行监听数据变化,这个getConten

Android ContentProvider、ContentResolver和ContentObserver的使用

1.ContentProvider.ContentResolver和ContentObserver ContentProvider是Android的四大组件之一,可见它在Android中的作用非同小可.它主要的作用是:实现各个应用程序之间的(跨应用)数据共享,比如联系人应用中就使用了ContentProvider,你在自己的应用中可以读取和修改联系人的数据,不过需要获得相应的权限.其实它也只是一个中间人,真正的数据源是文件或者SQLite等. 一个应用实现ContentProvider来提供内容

(Android review)ContentObserver

1.一个应用通过ContentObserver来观察自己所监听的数据(某个特定的URI)是否发生了变化2.ContentObserver放在Activity中.CotentProvider专门写一个类3.其实今天模拟这么一个场景.A应用通过原始应用的ContentProvider中提供的方法来操作原始应用的数据. .在原始应用中注册观察者来更新.也可以在B应用中注册观察者来更新 其实,ContentObserver的使用是比较简单的.主要有两个步骤: 1)通过ContentProvider来修改

ContentProvider+ContentObserver实例

最近正好用到,写个小Demo记录下: 清单文件: <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.gyz.mycontentprovidertest" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:mi

Android使用ContentObserver监听数据库变化(转自:http://www.blogjava.net/zhaojianhua/archive/2011/10/27/362204.html)

android 使用contentobserver监听数据库内容变化 android 使用contentobserver监听数据库内容变化 在 android中经常会用到改变数据库内容后再去使用数据库更新的内容,很多人会重新去query一遍,但是这样的问题就是程序会特别占内存,而且有可能 会搂关cursor而导致程序内存未释放等等.其实android内部提供了一种ContentObserver的东西来监听数据库内容的变化.ContentObserver 的构造函数需要一个参数Hanlder,因为

Android ContentProvider数据共享

一.构造一个自己的Provider实现App之间数据共享 1.我们先来了解一下   Uri(统一资源定位符) 定义:每一个Content Provider使用一个公开的URI唯一标示其数据集,Android所提供的ContentProvider都存放android.provider包中 结构:分为A.B.C.D四个部分 A:标准前缀,用来说明一个Content Provider控制这些数据,无法改变的: B:URI 的标识,唯一标识ContentProvider,外部调用者可以根据这个标识来找到

Android ContentProvider完整案例

ContentData类,提供数据常量: /** * 提供ContentProvider对外的各种常量,当外部数据需要访问的时候,就可以参考这些常量操作数据. * @author HB * */ public class ContentData { public static final String AUTHORITY = "hb.android.contentProvider"; public static final String DATABASE_NAME = "te

Android基础 : Android ContentProvider

Android 应用程序通过ContentProvider实现方式统一的数据共享功能. 外界的程序通过ContentResolver接口可以访问ContentProvider提供的数据,在Activity当中通过getContentResolver()可以得到当前应用的 ContentResolver实例. 参考文章 Android ContentProvider和getContentResolver

Android ContentProvider基本用法

转自:https://www.jianshu.com/p/601086916c8f 一.基本概念 ContentProvider是Android系统中提供的专门用户不同应用间进行数据共享的组件,提供了一套标准的接口用来获取以及操作数据,准许开发者把自己的应用数据根据需求开放给其他应用进行增删改查,而无须担心直接开放数据库权限而带来的安全问题.系统预置了许多ContentProvider用于获取用户数据,比如消息.联系人.日程表等. 二.ContentResolver 在ContentProvid