7.Android基础:四大组件之----->ContentProvider

来源:互联网 发布:haoduofuli新域名 编辑:程序博客网 时间:2024/06/06 01:53

ContentProvider:内容提供者

1.把私有数据共享给其他应用访问

2.使用内容提供者可以自己定义访问规则,选择私有数据中哪些共享出去,哪些不共享


内容提供者

1.应用的数据库是不允许其他应用访问的

2.内容提供者的作用就是让别的应用访问到你的私有数据
3. 自定义内容提供者,继承ContentProvider类,重写增删改查方法,在方法中写增删改查数据库的代码,举例增方法


重要方法

UriMatcher类

         NO_MATCH                                      创建URI的树的根节点。

         match(Uriuri):               尝试在一个网址中的路径匹配。

addURI(String authority,String path, int code):添加一个URI匹配,并且代码返回的时候,这个URI匹配。


下面举个简单的例子

配置清单文件

定义一个单元测试要测的包名下的类

<instrumentation android:name="android.test.InstrumentationTestRunner"android:targetPackage="com.mycontentprovider"></instrumentation>
添加单元测试使用类库
<uses-library android:name="android.test.runner"/>
在清单文件中定义内容提供者的标签,注意必须要有authorities属性,这是内容提供者的主机名,功能类似地址
<provider     android:name="com.mycontentprovider.PersonProvider"    android:authorities="com.people"    android:exported="true"></provider>
布局文件
<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=".MainActivity" >    <TextView        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="@string/hello_world" /></RelativeLayout>
内容提供者类
public class PersonProvider extends ContentProvider {private SQLiteDatabase db;//创建uri匹配器(判断是哪个表)UriMatcher um = new UriMatcher(UriMatcher.NO_MATCH);//添加匹配规则{//arg0:内容主机指定名//arg1:路径(哪个表)//arg2:匹配码um.addURI("com.people", "person", 1);//content://com.people/personum.addURI("com.people", "handsome", 2);um.addURI("com.people", "person/#", 3);//content://com.people/person/1}//内容提供者创建时调用@Overridepublic boolean onCreate() {// 打开数据库,拿到数据MyOpenHelper oh = new MyOpenHelper(getContext());db = oh.getWritableDatabase();return false;}//查询数据库@Overridepublic Cursor query(Uri uri, String[] projection, String selection,String[] selectionArgs, String sortOrder) {//arg1:要查哪个字段;//arg2:selection表示查询条件,就是查询里面的where语句,//arg3:selectionArgs是查询条件的值。//arg4:分组查询//arg7:进行排序Cursor cursor = null;if (um.match(uri) == 1) {// null:那个字段为空,设置即可cursor = db.query("person", projection, selection, selectionArgs, null, null, sortOrder, null);} else if (um.match(uri) == 2) {// null:那个字段为空,设置即可cursor = db.query("handsome", projection, selection, selectionArgs, null, null, sortOrder, null);} else if (um.match(uri) == 3) {//取出uri末尾携带的数字long id = ContentUris.parseId(uri);// null:那个字段为空,设置即可cursor = db.query("person", projection, "_id = ?", new String[]{"" + id}, null, null, sortOrder, null);} else {throw new IllegalArgumentException("uri传错了(表或者不存在)");}return cursor;}//插入数据库//value:其他应用要插得数据@Overridepublic Uri insert(Uri uri, ContentValues values) {if (um.match(uri) == 1) {// null:那个字段为空,设置即可db.insert("person", null, values);//数据库改变,内容提供者发出通知//arg0:通知发到哪个uri上,注册在这个uri上的内容观察者收到通知//arg0:观察者getContext().getContentResolver().notifyChange(uri, null);} else if (um.match(uri) == 2) {// null:那个字段为空,设置即可db.insert("handsome", null, values);getContext().getContentResolver().notifyChange(uri, null);} else {throw new IllegalArgumentException("uri传错了(表或者不存在)");}   return uri;}//删除数据库数据@Overridepublic int delete(Uri uri, String selection, String[] selectionArgs) {//删除多少行int i = db.delete("person", selection, selectionArgs);return i;}//修改数据库数据@Overridepublic int update(Uri uri, ContentValues values, String selection,String[] selectionArgs) {//修改多少行int i = db.update("person", values, selection, selectionArgs);return i;}//返回通过指定uri获取的数据的mimetype@Overridepublic String getType(Uri uri) {// TODO Auto-generated method stubif (um.match(uri) == 1) {//返回多条数据return "vnd.android.cursor.dir/person";} else if (um.match(uri) == 2) {//返回多条数据return "vnd.android.cursor.dir/handsome";} else if (um.match(uri) == 3) {//返回单条数据return "vnd.android.cursor.item/person";}return null;}}
单元框架测试类
public class Test extends AndroidTestCase {public void test() {//返回当前ActivityMyOpenHelper oh = new MyOpenHelper(getContext());//打开数据库写数据oh.getWritableDatabase();}}

数据库类

public class MyOpenHelper extends SQLiteOpenHelper {public MyOpenHelper(Context context) {//1为版本号super(context, "people.db", null, 2);// TODO Auto-generated constructor stub}//创建数据库调用@Overridepublic void onCreate(SQLiteDatabase db) {// 创建表db.execSQL("create table person(_id integer primary key autoincrement, name char(10), phone char(20), money integer(10))");}//升级数据库调用@Overridepublic void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {// 创建表db.execSQL("create table handsome(_id integer primary key autoincrement, name char(10), phone char(20))");}}

测试类

public class MainActivity extends Activity {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);}@Overridepublic boolean onCreateOptionsMenu(Menu menu) {// Inflate the menu; this adds items to the action bar if it is present.getMenuInflater().inflate(R.menu.main, menu);return true;}}
插入数据项目
布局文件

<LinearLayout 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=".MainActivity"     android:orientation="vertical">    <Button        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="插入"         android:onClick="insert"/>        <Button        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="删除"         android:onClick="delete"/>          <Button        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="修改"         android:onClick="update"/>             <Button        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="查询所有 "         android:onClick="query"/>               <Button        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="查询单条"         android:onClick="queryOne"/></LinearLayout>
测试类
public class MainActivity extends Activity {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);}//插入数据public void insert(View v) {//通过内容提供者把数据库插入01数据库//1.获取contentResolverContentResolver resolver = getContentResolver();//2.访问内容提供者,插入数据ContentValues values = new ContentValues();values.put("name", "hq");values.put("phone", 19950911);values.put("money", 13565);//arg0:指定内容提供者的主机名resolver.insert(Uri.parse("content://com.people/person"), values);//清空,防止新加入覆盖旧的values.clear();values.put("name", "jw");values.put("phone", 19950911);//arg0:指定内容提供者的主机名resolver.insert(Uri.parse("content://com.people/handsome"), values);}//删除数据public void delete(View v) {ContentResolver resolver = getContentResolver();    //删除几行数据int i = resolver.delete(Uri.parse("content://com.people"), "name = ?", new String[]{"jw"});    System.out.println(i);}//修改数据public void update(View v) {//返回给应用程序的封装方法实例。ContentResolver resolver = getContentResolver();ContentValues values = new ContentValues();//修改的第几条数据values.put("phone", "19940802");int i = resolver.update(Uri.parse("content://com.people"), values, "name = ?", new String[]{"hq"});System.out.println(i);}//查询数据库public void query(View v) {//返回给应用程序的封装方法实例。ContentResolver resolver = getContentResolver();Cursor cursor = resolver.query(Uri.parse("content://com.people/person"), null, null, null, null);while(cursor.moveToNext()) {String name = cursor.getString(1);String phone = cursor.getString(2);String money = cursor.getString(3);System.out.println("名字:" + name + " 电话:" + phone + " 工资:" + money);}}//查询数据库public void queryOne(View v) {//返回给应用程序的封装方法实例。ContentResolver resolver = getContentResolver();Cursor cursor = resolver.query(Uri.parse("content://com.people/person/1"), null, null, null, null);if(cursor.moveToNext()) {String name = cursor.getString(1);String phone = cursor.getString(2);String money = cursor.getString(3);System.out.println("名字:" + name + " 电话:" + phone + " 工资:" + money);}}}


0 0