Android ContentResolver使用

ContentResolver直译为内容解析器,Android中程序间数据的共享是通过Provider/Resolver进行的。提供数据(内容)的就叫Provider,Resovler提供接口对这个内容进行解读。

ContentResolver contentResolver = context.getContentResolver(); 

查询:

简单实例:(获取联系人姓名)

public void fetchAllContacts() {  
    ContentResolver contentResolver = context.getContentResolver();  
    Cursor cursor = contentResolver.query(android.provider.ContactsContract.Contacts.CONTENT_URI, null, null, null, null);  
    cursor.getCount();  
    while(cursor.moveToNext()) {  
        System.out.println(cursor.getString(cursor.getColumnIndex(android.provider.ContactsContract.Contacts._ID)));
		System.out.println(cursor.getString(cursor.getColumnIndex(android.provider.ContactsContract.Contacts.DISPLAY_NAME)));  
    }  
    cursor.close();  
} 
query API及参数解析:
public final Cursor query (Uri uri, String[] projection,String selection,String[] selectionArgs, String sortOrder)

    第一个参数,uri,uri是什么呢?好吧,上面我们提到了Android提供内容的叫Provider,那么在Android中怎么区分各个Provider?有提供联系人的,有提供图片的等等。所以就需要有一个唯一的标识来标识这个Provider,Uri就是这个标识,android.provider.ContactsContract.Contacts.CONTENT_URI就是提供联系人的内容提供者,可惜这个内容提供者提供的数据很少。
    第二个参数,projection,真不知道为什么要用这个单词,这个参数告诉Provider要返回的内容(列Column),比如Contacts Provider提供了联系人的ID和联系人的NAME等内容,如果我们只需要NAME,那么我们就应该使用:

Cursor cursor = contentResolver.query(android.provider.ContactsContract.Contacts.CONTENT_URI, new String[]{android.provider.ContactsContract.Contacts.DISPLAY_NAME}, null, null, null); 

    当然,下面打印的你就只能显示NAME了,因为你返回的结果不包含ID。用null表示返回Provider的所有内容(列Column)。
    第三个参数,selection,设置条件,相当于SQL语句中的where。null表示不进行筛选。如果我们只想返回名称为张三的数据,第三个参数应该设置为:

Cursor cursor = contentResolver.query(android.provider.ContactsContract.Contacts.CONTENT_URI, new String[]{android.provider.ContactsContract.Contacts.DISPLAY_NAME}, android.provider.ContactsContract.Contacts.DISPLAY_NAME + "='张三'", null, null); 

    第四个参数,selectionArgs,这个参数是要配合第三个参数使用的,如果你在第三个参数里面有?,那么你在selectionArgs写的数据就会替换掉?,

Cursor cursor = contentResolver.query(android.provider.ContactsContract.Contacts.CONTENT_URI, new String[]{android.provider.ContactsContract.Contacts.DISPLAY_NAME},   android.provider.ContactsContract.Contacts.DISPLAY_NAME + "=?", new String[]{"张三"}, null);  

    第五个参数,sortOrder,按照什么进行排序,相当于SQL语句中的Order by。如果想要结果按照ID的降序排列:

Cursor cursor = contentResolver.query(android.provider.ContactsContract.Contacts.CONTENT_URI, null, null,null, android.provider.ContactsContract.Contacts._ID + " DESC");  

    升序,其实默认排序是升序,+" ASC"写不写效果都一样:

Cursor cursor = contentResolver.query(android.provider.ContactsContract.Contacts.CONTENT_URI, null, null,null, android.provider.ContactsContract.Contacts._ID + " ASC");              

 

转载于:https://my.oschina.net/u/2320057/blog/758850

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值