ContentProvider数据共享方法的使用

ContentProvider 完全屏蔽的了数据提供者的数据存取方式,只要通过调用ContentProvider提供的借口就可以去所有的数据进行操作

ContentProvider数据模式类似于数据库的表,每一行都是一条数据,每一列都具有相同的数据类型,其通过URI来获取数据源,其使用的URI语法结构如下:

content:////

(content://)表示前缀,表示该URI用于ContentProvider定位资源,无须修改

表示授权者的名称,用来确定具体由哪一个Contentprovider来提供资源

表示路径,用来确定请求的是哪个数据集

例如:content://com.lonuery.mycontentprovider/abc  表示的就是在com.lonuery.mycontentprovider 包下的数据集abc


一:创建数据提供者

一般分为三步:1:继承ContentProvider,实现基本数据操作的六个函数 2:声明contenturi 实现UriMatcher 3:注册ContentProvider

下面是一个创建数据提供者的小例子:


public class MyProvider extends ContentProvider {

	Context context;
	SQLiteDatabase sdb;	
	private static UriMatcher uriMatche;//用来分析客户端那发来的额URI到底数个什么样的URI
	static {
		uriMatche = new UriMatcher(UriMatcher.NO_MATCH);
		uriMatche.addURI("com.lonuery.mycontextprovider","abc", 1);
		//authority 一般用包名指定(保证全球唯一)
		//path:取数据的路径,取数据的方式
		//code 匹配的结果
		//content://com.lonuery.DatabaseServer/abc/1  取单条数据,abc后数字为几就表示取几条数据,如果没有那就是多条
		//content://com.lonuery.DatabaseServer/abc  取多条数据
		uriMatche.addURI("com.lonuery.mycontextprovider", "abc/#", 2);
	};//初始化UriMatcher (添加的匹配的规则)	
	
	//做白日梦的人,上不了最前线,敢爱敢做的人超级精彩!
	@Override
	public int delete(Uri arg0, String arg1, String[] arg2) {
		String argId = arg0.getPathSegments().get(1);
		int delcount = sdb.delete("student", "_id=?", new String[]{argId});
		return delcount;
	}
	@Override
	public String getType(Uri arg0) {
		String retString = null;
		switch (uriMatche.match(arg0)) {
		case 2:
			retString = "vnd.android:cursor.item/vnd.com.lonuery.mycontextprovider.abc";
			break;
		case 1:
			retString="vnd.android:cursor.dir/vnd.com.lonuery.mycontextprovider.abc";
			break;
		default:
			break;
		}
		return retString;
	}
	@Override
	public Uri insert(Uri arg0, ContentValues arg1) {
		long retId = sdb.insert("Student", null,arg1);
		if(retId>0){
			Uri tempUri = Uri.parse("com.lonuery.mycontextprovider/abc");
			Uri newUri = ContentUris.withAppendedId(tempUri,retId);
			return newUri;
		}
		throw new SQLException("数据插入失败"+arg0);
	}
	/*
	 * 创建数据库*/
	@Override
	public boolean onCreate() {
                Context context = getContext();
                DatabaseHepler databaseHepler = new DatabaseHepler(context, "Student.db", null, 1);
		sdb = databaseHepler.getWritableDatabase();
		if(sdb!=null){
			return true;//创建成功则返回true
		}
		return false;
	}
	@Override
	public Cursor query(Uri arg0, String[] arg1, String arg2, String[] arg3,
			String arg4){
		
		Cursor cursor=null;
		switch (uriMatche.match(arg0)) {
		case 2://单条数据
                String argId = arg0.getPathSegments().get(1);
 cursor = sdb.query("Student", arg1, "_id=?", new String[]{argId},null, null, null);break;case 1://多条数据cursor =sdb.query("Student", null, null, null, null, null, arg4);break;default:break;}return cursor;}@Overridepublic int update(Uri arg0, ContentValues arg1, String arg2, String[] arg3) {String argId = arg0.getPathSegments().get(1);int upcount = sdb.update("School",arg1, "_id=?", new String[]{argId});return upcount;}public static class DatabaseHepler extends SQLiteOpenHelper{String str = "create table Student(_id Integer primary key autoincrement,name varchar(20),age varchar(20),sex varchar(20))";public DatabaseHepler(Context context, String name,CursorFactory factory, int version) {super(context, name, factory, version);// TODO Auto-generated constructor stub}@Overridepublic void onCreate(SQLiteDatabase arg0) {arg0.execSQL(str);}@Overridepublic void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {// TODO Auto-generated method stub}}}
 
  


通过content使用数据提供者的数据,进行,插入,单行查询,多行查询,删除行,更新行

public class ClientActivity extends Activity implements OnClickListener{

	Button btnInsert,btnQuerySingle,btnQueryMore,btnDelete,btnUpDate;
	TextView tv;
	EditText et;
	ContentResolver cr;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_client);
        
        cr = getContentResolver();//得到数据共享的客户端
        
        btnInsert = (Button)findViewById(R.id.button1);
        btnQuerySingle =(Button)findViewById(R.id.button2);
        btnQueryMore =(Button)findViewById(R.id.button3);
        btnUpDate =(Button)findViewById(R.id.button4);
        btnDelete =(Button)findViewById(R.id.button5);
        tv =(TextView)findViewById(R.id.textView1);
        et =(EditText)findViewById(R.id.editText1);
        
        btnInsert.setOnClickListener(this);
        btnQueryMore.setOnClickListener(this);
        btnQuerySingle.setOnClickListener(this);
        btnUpDate.setOnClickListener(this);
        btnDelete.setOnClickListener(this);     
    }
	@Override
	public void onClick(View arg0) {
		switch (arg0.getId()) {
		case R.id.button1:
			String baseuri = "content://com.lonuery.mycontextprovider/abc";
			Uri uri = Uri.parse(baseuri);
			ContentValues cv = new ContentValues();
			cv.put("name", "你妹");
			cv.put("age", "23");
			cv.put("sex", "男");
			cr.insert(uri, cv);
			break;
		case R.id.button2:
			String queryBaseUri = "content://com.lonuery.mycontextprovider/abc";
			String id = et.getText().toString();
			String queryOneUri = queryBaseUri + "/" +  id;
			// content://com.newer.DataBaseServer/abc/7
			Cursor cursorOne 
				= cr.query(Uri.parse(queryOneUri), null, null, null, null);
			if (cursorOne.moveToFirst()) {
				String idStr =cursorOne.getString(cursorOne.getColumnIndex("_id"));
				String name =cursorOne.getString(cursorOne.getColumnIndex("name"));
				String sex =cursorOne.getString(cursorOne.getColumnIndex("sex"));
				String age =cursorOne.getString(cursorOne.getColumnIndex("age"));
				tv.setText(" "+idStr + "  " + name + " " + sex + "  " + age + " \n");
			}
			break;
		case R.id.button3:
			String queryAllUri = "content://com.lonuery.mycontextprovider/abc";
			Cursor cursor = cr.query(Uri.parse(queryAllUri), null, null, null, null);
			tv.setText("");
			if (cursor.moveToFirst()) {
				do {
					String idMany =cursor.getString(cursor.getColumnIndex("_id"));
					String name =cursor.getString(cursor.getColumnIndex("name"));
					String sex =cursor.getString(cursor.getColumnIndex("sex"));
					String age =cursor.getString(cursor.getColumnIndex("age"));
					tv.append(" "+idMany + "  " + name + " " + sex + "  " + age + " \n");
				} while(cursor.moveToNext());
			}
			break;
		case R.id.button5:
			String queryBaseUri2 = "content://com.lonuery.mycontextprovider/abc";
			String delId = et.getText().toString();
			String delOneUri = queryBaseUri2 + "/" +  delId;
			cr.delete(Uri.parse(delOneUri), null, null);
			break;
		case R.id.button4:
			String updataBaseUri="content://com.lonuery.mycontextprovider/abc";
			String updataColumn = et.getText().toString();
			ContentValues updata = new ContentValues();
			updata.put("sex",updataColumn);
			cr.update(Uri.parse(updataBaseUri), updata,null,null);
			break;
		default:
			break;		
		}		
	}   
}





你可能感兴趣的:(ContentProvider数据共享方法的使用)