Content Provider主要用于在不同的应用程序之间呈现数据共享的功能.
ContactTest:
//访问系统电话博联系人数据
ListView contact_view;
ArrayAdapter adapter;
List contactList=new ArrayList();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
contact_view= (ListView) findViewById(R.id.contacts_view);
adapter=new ArrayAdapter(this,android.R.layout.simple_list_item_1,contactList);
//android.R.layout.simple_list_item_1是一个系统自带的布局文件里面只有一个TextView控件
contact_view.setAdapter(adapter);
readContact();
}
private void readContact() {
Cursor cursor=null;
try{
/*方法参数:1.URI
2.Projection 指定查询列名
3.selection 指定where的约束条件
4.为where中的占位符提供具体的值
5.指定查询结果的排序方式
*/
cursor=getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,null,null,null);
//ContactsContract.CommonDataKinds.Phone.CONTENT_URI系统封装类直接引用做uri
while(cursor.moveToNext()){
//moveTonext 和 moveToFirst指向的都是第一条记录的前面
String person_name=cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone
.DISPLAY_NAME));//值为电话博联系人姓名
String person_number=cursor.getString(cursor.getColumnIndex(ContactsContract
.CommonDataKinds.Phone.NUMBER));
contactList.add(person_name+"/n"+person_number);
//最后还要在manifestS中加入权限permission.READ_CONTACTS
}
}
catch(Exception e){
e.printStackTrace();
}finally {
if(cursor!=null){
cursor.close();
}
}
自定义内容提供器:
ContentProvider 类中有六个抽象方法,使用子类继承它的时候,需要将这六个方法全部重写。
onCreate():
初始化内容提供器的时候调用。通常会在这里完成对数据库的创建和升级等操作,返回 true 表示内容提供器初始化成功,返回 false 则表示失败。
注意,只有当存在 ContentResolver 尝试访问我们程序中的数据时,内容提供器才会被初始化。
query():
从内容提供器中查询数据。使用 uri 参数来确定查询哪张表,projection 参数用于确定查询哪些列,selection 和 selectionArgs 参数用于约束查询哪些行,sortOrder 参数用于对结果进行排序,查询的结果存放在 Cursor 对象中返回。
insert():
向内容提供器中添加一条数据。使用 uri 参数来确定要添加到的表,待添加的数据保存在 values 参数中。添加完成后,返回一个用于表示这条新记录的 URI。
update():
更新内容提供器中已有的数据。使用 uri 参数来确定更新哪一张表中的数据,新数据保存在 values 参数中,selection 和 selectionArgs 参数用于约束更新哪些行,受影响的行数将作为返回值返回。
delete():
从内容提供器中删除数据。使用 uri 参数来确定删除哪一张表中的数据,selection 和 selectionArgs 参数用于约束删除哪些行,被删除的行数将作为返回值返回。
getType():
根据传入的内容 URI 来返回相应的 MIME 类型。
getType() 方法。它是所有的内容提供器都必须提供的一个方法,用于获取 Uri 对象所对应的 MIME 类型:
1. 必须以 vnd 开头。
2. 如果内容 URI 以路径结尾,则后接 android.cursor.dir/,如果内容 URI 以 id 结尾,则后接 android.cursor.item/。
3. 最后接上 vnd..。
例如:”vnd.android.cursor.dir/vnd.com.example.app.provider.table”
或:”vnd.android.cursor.item/vnd.com.example.app.provider.table”
UriMatcher 中提供了一个 addURI() 方法,这个方法接收三个参数,可以分别把权限、路径和一个自定义代码传进去
UriMatcher uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
uriMatcher.addURI(“com.example.app.provider”, “table/#” , TABLE_ITEM);
switch( uriMatcher.match( uri ) ){ … }
PS:争取每天写一点,把自己容易忘的要点都记录下来
FIGHTING!!!!