【问题标题】:Confused on how to query Contacts in Android对如何在 Android 中查询联系人感到困惑
【发布时间】:2011-08-03 21:30:04
【问题描述】:
我正在制作一个使用联系人的 Android 应用程序。好消息是我设法使它与许多教程中看到的 Contacts.Phones 一起工作。问题是 Contacts.Phones 已被弃用,取而代之的是 ContactsContract。我的应用程序需要从 Android 1.5+ 开始工作。
我需要做一些简单的操作,比如:
- 查询所有联系人
- 查询特定联系人
- 备份所有联系人
考虑到我需要让应用程序在所有版本的 android 上运行,最好的方法是什么?我是否需要在手机上检查当前的 api 级别并有 2 个代码块,一个在 api 5 之前一个在 api 5 之后?
【问题讨论】:
标签:
android
android-contentprovider
contact
【解决方案1】:
这是一个可选的解决方案
int apiVersion = android.os.Build.VERSION.SDK_INT;
if(apiVersion < 5) {
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(People.CONTENT_URI,
null, null, null, null);
if (cur.getCount() > 0) {
while (cur.moveToNext()) {
String id = cur.getString(cur.getColumnIndex(People._ID));
String name = cur.getString(cur.getColumnIndex(People.DISPLAY_NAME));
}
}
} else {
String columns[] = new String[]{ ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME };
Cursor cursor = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI,
columns,
null,
null,
ContactsContract.Data.DISPLAY_NAME + " COLLATE LOCALIZED ASC");
if (cursor.getCount() > 0) {
while (cursor.moveToNext()) {
long id = Long.parseLong(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID)));
String displayName = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)).trim();
}
}
}
这里有一个制作应用程序Supporting the old and new APIs in the same application的教程,这对你有帮助。
【解决方案2】:
使用ContentResolver。试试这个代码:
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
null, null, null, null);
if (cur.getCount() > 0) {
while (cur.moveToNext()) {
String id = cur.getString(
cur.getColumnIndex(ContactsContract.Contacts._ID));
String name = cur.getString(
cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
if (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
//Query phone here. Covered next
}
}
}