需求:
很多需求都需要加载手机联系人,一次性加载全部的联系人有比较耗时,所以分页加载时比较理想的。分页加载数据需要考虑的就是数据的排序问题,保证同样的时间每次query的时候排序要一样的,不然分页就没有意义(数据紊乱的现象)。分页须知:每页加载数,数据源总数,数据源排序,共多少页。基本好像就这些。如果数据考虑到增删操作的话,分页就复杂一些。注意加访问的权限。
0、效果图
1、权限
<uses-permission android:name="android.permission.READ_CONTACTS" />
2、获取联系人总数
public int getAllPhoneNums() {
int num = 0;
Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
String[] projection = {ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME, ContactsContract.CommonDataKinds.Phone.DATA1,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID};
Cursor cursor = mContext.getContentResolver().query(uri, projection, null, null, null);
if (null != cursor) {
num = cursor.getCount();
cursor.close();
}
return num;
}
3、分页加载数据
/**
* 分页查询系统联系人信息
*
* @param pageSize 每页最大的数目
* @param page 页数
* @return
*/
public Page<List<ContactsPerson>> getContactsByPage(int pageSize, int page) {
Page<List<ContactsPerson>> tempPage = new Page<>();
tempPage.data = new ArrayList<ContactsPerson>();
Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
String[] projection = {ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.DATA1, ContactsContract.CommonDataKinds.Phone.CONTACT_ID};
tempPage.count = getAllPhoneNums();
tempPage.pages = tempPage.count / pageSize + (tempPage.count % pageSize == 0 ? 0 : 1);
if (page < 1) {
page = 1;
} else if (page > tempPage.pages) {
page = tempPage.pages;
}
tempPage.page = page;
tempPage.limit = pageSize <= 0 ? 10 : pageSize;
int currentOffset = (tempPage.page - 1) * tempPage.limit;
Cursor cursor = mContext.getContentResolver().query(uri, projection, null, null, ContactsContract.Contacts._ID + " ASC limit " + pageSize + " offset " + currentOffset);
if (cursor != null) {
while (cursor.moveToNext()) {
ContactsPerson info = new ContactsPerson();
info.setName(cursor.getString(0));
info.setPhoneNumber(cursor.getString(1));
info.setId(cursor.getLong(2));
info.setHeadUrl(ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, info.getId()).toString());
tempPage.data.add(info);
Log.e("ContactsPerson: ", info.toString());
info = null;
}
Log.e("ContactsPerson: ", tempPage.toString());
cursor.close();
}
return tempPage;
}
以上贴的是部分核心代码。完整Demo请点击。