《sqlite数据库与ContentprovIDer(2)》要点:
本文介绍了sqlite数据库与ContentprovIDer(2),希望对您有用。如果有疑问,可以联系我们。
ContentProvIDer:
在创建ContentProvIDer时,必要首先使用数据库、文件系统或网络实现底层存储功能,
然后在继承ContentProvIDer的类中实现基本数据 *** 作的接口函数,包含添加、删除、查找和更新等功能.
调用者不能够直接调用ContentProvIDer的接口函数,而必要使用ContentResolver对象,
通过URI间接调用ContentProvIDer.下图是ContentProvIDer调用关系.
URI:
URI是通用资源标志符(Uniform Resource IDentifIEr),用来定位任何远程或当地的可用资源
ContentProvIDer使用的URI语法布局如下
content://<authority>/<data_path>/<ID>
content://是通用前缀,表现该URI用于ContentProvIDer定位资源,无需修改.
<authority>是授权者名称,用来确定具体由哪一个ContentProvIDer提供资源.因此,一般<authority>都由类的小写全称组成,以保证唯一性.
<data_path>是数据路径,用来确定哀求的是哪个数据集.
例如:
content://edu.hrbeu.peopleprovIDer/people/3
可以省略ID(/3)部门那么意味着整个数据.
UriMatcher:
在新构造的ContentProvIDer类中,通过构造一个UriMatcher,判断URI是单条数据还是多条数据.
public voID addURI (String authority,String path,int code)
authority表现匹配的授权者名称
path表现数据路径
#可以代表任何数字 (content://<authority>/<data_path>/#)
code表现返回代码(uriMatcher.match(uri))的返回值)
注册ContentProvIDer :
<provIDer androID:name = ".PeopleProvIDer" androID:authoritIEs = "edu.hrbeu.peopleprovIDer"/>
实例:
ContentProvIDer一般用于两个分歧的进程之间的数据共享.
假设我们有一个新的工程(app),在此工程中创建一个people.db数据库,然后通过自定义了一个ContentProvIDer来共享数据库中的data.我们可以通过注册provIDer时用到的authority在配合db path之类的来连接(content://<authority>/<data_path>/#)读取内容提供者(分歧进程)的数据.首先是步骤1:
*只要在AndroIDManifast中注册provIDer就会执行对应的provIDer类.无需再MainActivity中调用或无需直接调用自定义的new provIDer.
即系统自动会加载调用PeopleProvIDer类.
继承ContentProvIDer时代码如下:
import androID.content.*;import androID.database.Cursor;import androID.net.Uri; public class PeopleProvIDer extends ContentProvIDer{ @OverrIDe public int delete(Uri uri,String selection,String[] selectionArgs) { // Todo auto-generated method stub return 0; } @OverrIDe public String getType(Uri uri) { // Todo auto-generated method stub return null; } @OverrIDe public Uri insert(Uri uri,ContentValues values) { // Todo auto-generated method stub return null; } @OverrIDe public boolean onCreate { // Todo auto-generated method stub return false; } @OverrIDe public Cursor query(Uri uri,String[] projection,String[] selectionArgs,String sortOrder) { // Todo auto-generated method stub return null; } @OverrIDe public int update(Uri uri,ContentValues values,String[] selectionArgs) { // Todo auto-generated method stub return 0; }}
类似数据库 *** 作.可以这么理解,相对来说好理解.
开始贴代码...
package edu.hrbeu.contentprovIDerdemo; import androID.content.ContentProvIDer;import androID.content.ContentUris;import androID.content.ContentValues;import androID.content.Context;import androID.content.UriMatcher;import androID.database.Cursor;import androID.database.sqlException;import androID.database.sqlite.sqliteDatabase;import androID.database.sqlite.sqliteDatabase.CursorFactory;import androID.database.sqlite.sqliteOpenHelper;import androID.database.sqlite.sqlitequeryBuilder;import androID.net.Uri;public class PeopleProvIDer extends ContentProvIDer { private static final String DB_name = "people.db"; private static final String DB_table = "peopleinfo"; private static final int DB_VERSION = 1; private sqliteDatabase db; private DBOpenHelper dbOpenHelper; private static final int MulTIPLE_PEOPLE = 1; private static final int SINGLE_PEOPLE = 2; private static final UriMatcher uriMatcher; static { uriMatcher = new UriMatcher(UriMatcher.NO_MATCH); uriMatcher.addURI(People.AUTHORITY,People.PATH_MulTIPLE,MulTIPLE_PEOPLE); uriMatcher.addURI(People.AUTHORITY,People.PATH_SINGLE,SINGLE_PEOPLE); } @OverrIDe public boolean onCreate { // Todo auto-generated method stub Context context = getContext; dbOpenHelper = new DBOpenHelper(context,DB_name,null,DB_VERSION); db = dbOpenHelper.getWritableDatabase; if (db == null) return false; else return true; } @OverrIDe public Cursor query(Uri uri,String sortOrder) { // Todo auto-generated method stub sqlitequeryBuilder qb = new sqlitequeryBuilder; qb.settables(DB_table); switch(uriMatcher.match(uri)){ case SINGLE_PEOPLE: qb.appenDWhere(People.KEY_ID + "=" + uri.getPathSegments.get(1)); break; default: break; } Cursor cursor = qb.query(db,projection,selection,selectionArgs,sortOrder); cursor.setNotificationUri(getContext.getContentResolver,uri); return cursor; } @OverrIDe public String getType(Uri uri) { // Todo auto-generated method stub switch(uriMatcher.match(uri)){ case MulTIPLE_PEOPLE: return People.mine_TYPE_MulTIPLE; case SINGLE_PEOPLE: return People.mine_TYPE_SINGLE; default: throw new IllegalArgumentException("Unkown uri:"+uri);} } @OverrIDe public Uri insert(Uri uri,ContentValues values) { // Todo auto-generated method stub long ID = db.insert(DB_table,values); if ( ID > 0 ){ Uri newUri = ContentUris.withAppendedID(People.CONTENT_URI,ID); getContext.getContentResolver.notifyChange(newUri,null); return newUri; } throw new sqlException("Failed to insert row into " + uri); } @OverrIDe public int delete(Uri uri,String[] selectionArgs) { // Todo auto-generated method stub int count = 0; switch(uriMatcher.match(uri)){ case MulTIPLE_PEOPLE: count = db.delete(DB_table,selectionArgs); break; case SINGLE_PEOPLE: String segment = uri.getPathSegments.get(1); count = db.delete(DB_table,People.KEY_ID + "=" + segment,selectionArgs); break; default: throw new IllegalArgumentException("Unsupported URI:" + uri);} getContext.getContentResolver.notifyChange(uri,null); return count; } @OverrIDe public int update(Uri uri,String[] selectionArgs) { // Todo auto-generated method stub int count; switch(uriMatcher.match(uri)){ case MulTIPLE_PEOPLE: count = db.update(DB_table,values,selectionArgs); break; case SINGLE_PEOPLE: String segment = uri.getPathSegments.get(1); count = db.update(DB_table,People.KEY_ID+"="+segment,selectionArgs); break; default: throw new IllegalArgumentException("UnkNow URI:" + uri); } getContext.getContentResolver.notifyChange(uri,null); return count; } private static class DBOpenHelper extends sqliteOpenHelper { public DBOpenHelper(Context context,String name,CursorFactory factory,int version) { super(context,name,factory,version); } private static final String DB_CREATE = "create table " + DB_table + " (" + People.KEY_ID + " integer primary key autoincrement," + People.KEY_name+ " text not null," + People.KEY_AGE+ " integer," + People.KEY_HEIGHT + " float);"; @OverrIDe public voID onCreate(sqliteDatabase _db) { // Todo auto-generated method stub _db.execsql(DB_CREATE); } @OverrIDe public voID onUpgrade(sqliteDatabase _db,int oldVersion,int newVersion) { // Todo auto-generated method stub _db.execsql("DROP table IF EXISTS " + DB_table); onCreate(_db); } } }
package edu.hrbeu.contentprovIDerdemo;import androID.net.Uri; public class People{ public static final String MIME_DIR_PREFIX = "vnd.androID.cursor.dir"; public static final String MIME_ITEM_PREFIX = "vnd.androID.cursor.item"; public static final String mine_ITEM = "vnd.hrbeu.people"; public static final String mine_TYPE_SINGLE = MIME_ITEM_PREFIX + "/" + mine_ITEM; public static final String mine_TYPE_MulTIPLE = MIME_DIR_PREFIX + "/" + mine_ITEM; public static final String AUTHORITY = "edu.hrbeu.peopleprovIDer"; public static final String PATH_SINGLE = "people/#"; public static final String PATH_MulTIPLE = "people"; public static final String CONTENT_URI_STRING = "content://" + AUTHORITY + "/" + PATH_MulTIPLE; public static final Uri CONTENT_URI = Uri.parse(CONTENT_URI_STRING); public static final String KEY_ID = "_ID"; public static final String KEY_name = "name"; public static final String KEY_AGE = "age"; public static final String KEY_HEIGHT = "height";}
MainActivity是空的...不贴出来了.
运行成果没有任何内容,因为仅是添加了一个provIDer.
看一下步调2:
在另一个App中调用此ContentProvIDer.
无需再AndroIDManifast中注册provIDer.
只需对应步骤1中的People类里的静态变量是完全匹配的便是可以了.
也就是说URI需要与我们自定义的ContentProvIDer坚持一致.
package edu.hrbeu.contentresolverdemo;import androID.net.Uri; public class People{ public static final String MIME_DIR_PREFIX = "vnd.androID.cursor.dir"; public static final String MIME_ITEM_PREFIX = "vnd.androID.cursor.item"; public static final String mine_ITEM = "vnd.hrbeu.people"; public static final String mine_TYPE_SINGLE = MIME_ITEM_PREFIX + "/" + mine_ITEM; public static final String mine_TYPE_MulTIPLE = MIME_DIR_PREFIX + "/" + mine_ITEM; public static final String AUTHORITY = "edu.hrbeu.peopleprovIDer"; public static final String PATH_SINGLE = "people/#"; public static final String PATH_MulTIPLE = "people"; public static final String CONTENT_URI_STRING = "content://" + AUTHORITY + "/" + PATH_MulTIPLE; public static final Uri CONTENT_URI = Uri.parse(CONTENT_URI_STRING); public static final String KEY_ID = "_ID"; public static final String KEY_name = "name"; public static final String KEY_AGE = "age"; public static final String KEY_HEIGHT = "height";}
*** 作Contentpriver提供的数据我们必要用到ContentResolver:
package edu.hrbeu.contentresolverdemo;import androID.app.Activity;import androID.os.Bundle;import androID.vIEw.Menu;import androID.vIEw.MenuItem;import androID.content.ContentResolver;import androID.content.ContentValues;import androID.database.Cursor;import androID.net.Uri;import androID.vIEw.VIEw;import androID.vIEw.VIEw.OnClickListener;import androID.Widget.button;import androID.Widget.EditText;import androID.Widget.TextVIEw;public class ContentResolverDemo extends Activity { private EditText nameText; private EditText ageText; private EditText heightText; private EditText IDEntry; private TextVIEw labelVIEw; private TextVIEw displayVIEw; private ContentResolver resolver; @OverrIDe protected voID onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentVIEw(R.layout.activity_content_resolver_demo); nameText = (EditText) findVIEwByID(R.ID.name); ageText = (EditText) findVIEwByID(R.ID.age); heightText = (EditText) findVIEwByID(R.ID.hight); IDEntry = (EditText) findVIEwByID(R.ID.ID); labelVIEw = (TextVIEw) findVIEwByID(R.ID.label); displayVIEw = (TextVIEw) findVIEwByID(R.ID.display); button addbutton = (button) findVIEwByID(R.ID.button1); button queryAllbutton = (button) findVIEwByID(R.ID.button2); button clearbutton = (button) findVIEwByID(R.ID.button3); button querybutton = (button) findVIEwByID(R.ID.button6); button deletebutton = (button) findVIEwByID(R.ID.button5); button updatebutton = (button) findVIEwByID(R.ID.button7); resolver = this.getContentResolver; addbutton.setonClickListener(new OnClickListener { @OverrIDe public voID onClick(VIEw v) { // Todo auto-generated method stub ContentValues values = new ContentValues; values.put(People.KEY_name,nameText.getText.toString); values.put(People.KEY_AGE,Integer.parseInt(ageText.getText.toString)); values.put(People.KEY_HEIGHT,float.parsefloat(heightText.getText.toString)); Uri newUri = resolver.insert(People.CONTENT_URI,values); labelVIEw.setText("添加成功,URI:" + newUri); } }); queryAllbutton.setonClickListener(new OnClickListener { @OverrIDe public voID onClick(VIEw v) { // Todo auto-generated method stub Cursor cursor = resolver.query(People.CONTENT_URI,new String[] { People.KEY_ID,People.KEY_name,People.KEY_AGE,People.KEY_HEIGHT },null); if (cursor == null) { labelVIEw.setText("数据库中没有数据"); return; } labelVIEw.setText("数据库:" + String.valueOf(cursor.getCount) + "条记录"); String msg = ""; if (cursor.movetoFirst) { do { msg += "ID:" + cursor.getInt(cursor .getColumnIndex(People.KEY_ID)) + ","; msg += "姓名:" + cursor.getString(cursor .getColumnIndex(People.KEY_name)) + ","; msg += "年龄:" + cursor.getInt(cursor .getColumnIndex(People.KEY_AGE)) + ","; msg += "身高:" + cursor.getfloat(cursor .getColumnIndex(People.KEY_HEIGHT)) + "\n"; } while (cursor.movetoNext); } displayVIEw.setText(msg); } }); clearbutton.setonClickListener(new OnClickListener { @OverrIDe public voID onClick(VIEw v) { // Todo auto-generated method stub displayVIEw.setText(""); } }); querybutton.setonClickListener(new OnClickListener { @OverrIDe public voID onClick(VIEw v) { // Todo auto-generated method stub Uri uri = Uri.parse(People.CONTENT_URI_STRING + "/" + IDEntry.getText.toString); Cursor cursor = resolver.query(uri,null); if (cursor == null) { labelVIEw.setText("数据库中没有数据"); return; } String msg = ""; if (cursor.movetoFirst) { msg += "ID:" + cursor.getInt(cursor .getColumnIndex(People.KEY_ID)) + ","; msg += "身高:" + cursor.getfloat(cursor .getColumnIndex(People.KEY_HEIGHT)) + "\n"; } labelVIEw.setText("数据库:"); displayVIEw.setText(msg); } }); deletebutton.setonClickListener(new OnClickListener { @OverrIDe public voID onClick(VIEw v) { // Todo auto-generated method stub Uri uri = Uri.parse(People.CONTENT_URI_STRING + "/" + IDEntry.getText.toString); int result = resolver.delete(uri,null); String msg = "删除ID为" + IDEntry.getText.toString + "的数据" + (result > 0 ? "成功" : "失败"); labelVIEw.setText(msg); } }); updatebutton.setonClickListener(new OnClickListener { @OverrIDe public voID onClick(VIEw v) { // Todo auto-generated method stub ContentValues values = new ContentValues; values.put(People.KEY_name,float.parsefloat(heightText.getText.toString)); Uri uri = Uri.parse(People.CONTENT_URI_STRING + "/" + IDEntry.getText.toString); int result = resolver.update(uri,null); String msg = "更新ID为" + IDEntry.getText.toString + "的数据" + (result > 0 ? "成功" : "失败"); labelVIEw.setText(msg); } }); } @OverrIDe public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater.inflate(R.menu.content_resolver_demo,menu); return true; } @OverrIDe public boolean onoptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button,so long // as you specify a parent activity in AndroIDManifest.xml. int ID = item.getItemID; if (ID == R.ID.action_settings) { return true; } return super.onoptionsItemSelected(item); }}
事成相识的结构文件也附上:
<relativeLayout xmlns:androID="http://schemas.androID.com/apk/res/androID" xmlns:tools="http://schemas.androID.com/tools" androID:layout_wIDth="match_parent" androID:layout_height="match_parent" androID:paddingBottom="@dimen/activity_vertical_margin" androID:paddingleft="@dimen/activity_horizontal_margin" androID:paddingRight="@dimen/activity_horizontal_margin" androID:paddingtop="@dimen/activity_vertical_margin" tools:context="edu.hrbeu.contentresolverdemo.ContentResolverDemo" > <TextVIEw androID:ID="@+ID/Username" androID:layout_height="wrap_content" androID:layout_wIDth="fill_parent" androID:text="用户名:"> </TextVIEw> <EditText androID:ID="@+ID/name" androID:layout_wIDth="fill_parent" androID:layout_height="wrap_content" androID:layout_below="@ID/Username" > </EditText> <TextVIEw androID:ID="@+ID/Userage" androID:layout_height="wrap_content" androID:layout_wIDth="fill_parent" androID:layout_below="@ID/name" androID:text="年龄:"> </TextVIEw> <EditText androID:ID="@+ID/age" androID:layout_height="wrap_content" androID:layout_wIDth="fill_parent" androID:layout_below="@ID/Userage"> </EditText> <TextVIEw androID:ID="@+ID/Userhight" androID:layout_height="wrap_content" androID:layout_wIDth="fill_parent" androID:layout_below="@ID/age" androID:text="身高:"> </TextVIEw> <EditText androID:ID="@+ID/hight" androID:layout_height="wrap_content" androID:layout_wIDth="fill_parent" androID:layout_below="@ID/Userhight"> </EditText> <button androID:ID="@+ID/button2" androID:layout_wIDth="wrap_content" androID:layout_height="wrap_content" androID:layout_alignBaseline="@+ID/button1" androID:layout_alignBottom="@+ID/button1" androID:layout_centerHorizontal="true" androID:text="全部显示" /> <button androID:ID="@+ID/button3" androID:layout_wIDth="wrap_content" androID:layout_height="wrap_content" androID:layout_alignBaseline="@+ID/button2" androID:layout_alignBottom="@+ID/button2" androID:layout_alignRight="@+ID/hight" androID:text="清除显示" /> <TextVIEw androID:ID="@+ID/UserID" androID:layout_height="wrap_content" androID:layout_wIDth="fill_parent" androID:layout_below="@ID/button1" androID:text="ID:"> </TextVIEw> <EditText androID:ID="@+ID/ID" androID:layout_height="wrap_content" androID:layout_wIDth="fill_parent" androID:layout_below="@ID/UserID"> </EditText> <button androID:ID="@+ID/button6" androID:layout_wIDth="wrap_content" androID:layout_height="wrap_content" androID:layout_alignBaseline="@+ID/button5" androID:layout_alignBottom="@+ID/button5" androID:layout_alignleft="@+ID/button2" androID:text="ID查询" /> <button androID:ID="@+ID/button7" androID:layout_wIDth="wrap_content" androID:layout_height="wrap_content" androID:layout_alignBaseline="@+ID/button6" androID:layout_alignBottom="@+ID/button6" androID:layout_alignleft="@+ID/button3" androID:text="ID更新" /> <button androID:ID="@+ID/button1" androID:layout_wIDth="wrap_content" androID:layout_height="wrap_content" androID:layout_below="@+ID/hight" androID:text="添加数据" /> <button androID:ID="@+ID/button5" androID:layout_wIDth="wrap_content" androID:layout_height="wrap_content" androID:layout_alignleft="@+ID/ID" androID:layout_below="@+ID/ID" androID:text="ID删除" /> <TextVIEw androID:ID="@+ID/display" androID:layout_wIDth="fill_parent" androID:layout_height="wrap_content" androID:layout_alignleft="@+ID/label" androID:layout_below="@+ID/label" androID:layout_margintop="23dp" /> <TextVIEw androID:ID="@+ID/label" androID:layout_wIDth="fill_parent" androID:layout_height="wrap_content" androID:layout_alignleft="@+ID/button5" androID:layout_below="@+ID/button6" androID:layout_margintop="14dp" /></relativeLayout>
运行成果:
欢迎参与《sqlite数据库与ContentprovIDer(2)》讨论,分享您的想法,内存溢出PHP学院为您提供专业教程。
总结以上是内存溢出为你收集整理的SQLite数据库与Contentprovider(2)全部内容,希望文章能够帮你解决SQLite数据库与Contentprovider(2)所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)