我想保存的所有联系人的电话号码在一个ArrayList,但我不能找到一种方法如何。 有没有办法让他们,而不是接他们一个个ContactsContract?
Answer 1:
ContentResolver cr = mContext.getContentResolver(); //Activity/Application android.content.Context
Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
if(cursor.moveToFirst())
{
ArrayList<String> alContacts = new ArrayList<String>();
do
{
String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
if(Integer.parseInt(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0)
{
Cursor pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null,ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = ?",new String[]{ id }, null);
while (pCur.moveToNext())
{
String contactNumber = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
alContacts.add(contactNumber);
break;
}
pCur.close();
}
} while (cursor.moveToNext()) ;
}
Answer 2:
试试这个:
Cursor managedCursor = getContentResolver()
.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
new String[] {Phone._ID, Phone.DISPLAY_NAME, Phone.NUMBER}, null, null, Phone.DISPLAY_NAME + " ASC");
并通过光标穿越,你可以存储在你选择的任何数据结构,所有这些数据。
Answer 3:
此代码会比在应答码快得多,因为你不为每个联系人的其他查询。
private static final String CONTACT_ID = ContactsContract.Contacts._ID;
private static final String HAS_PHONE_NUMBER = ContactsContract.Contacts.HAS_PHONE_NUMBER;
private static final String PHONE_NUMBER = ContactsContract.CommonDataKinds.Phone.NUMBER;
private static final String PHONE_CONTACT_ID = ContactsContract.CommonDataKinds.Phone.CONTACT_ID;
public static ArrayList<String> getAll(Context context) {
ContentResolver cr = context.getContentResolver();
Cursor pCur = cr.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
new String[]{PHONE_NUMBER, PHONE_CONTACT_ID},
null,
null,
null
);
if(pCur != null){
if(pCur.getCount() > 0) {
HashMap<Integer, ArrayList<String>> phones = new HashMap<>();
while (pCur.moveToNext()) {
Integer contactId = pCur.getInt(pCur.getColumnIndex(PHONE_CONTACT_ID));
ArrayList<String> curPhones = new ArrayList<>();
if (phones.containsKey(contactId)) {
curPhones = phones.get(contactId);
}
curPhones.add(pCur.getString(pCur.getColumnIndex(PHONE_NUMBER)));
phones.put(contactId, curPhones);
}
Cursor cur = cr.query(
ContactsContract.Contacts.CONTENT_URI,
new String[]{CONTACT_ID, HAS_PHONE_NUMBER},
HAS_PHONE_NUMBER + " > 0",
null,null);
if (cur != null) {
if (cur.getCount() > 0) {
ArrayList<String> contacts = new ArrayList<>();
while (cur.moveToNext()) {
int id = cur.getInt(cur.getColumnIndex(CONTACT_ID));
if(phones.containsKey(id)) {
contacts.addAll(phones.get(id));
}
}
return contacts;
}
cur.close();
}
}
pCur.close();
}
return null;
}
Answer 4:
试试这也让所有的联系人。
Cursor cursor = context.getContentResolver().query(Phone.CONTENT_URI, null , null , null,
"upper("+Phone.DISPLAY_NAME + ") ASC");
文章来源: Android get all contacts telephone number in ArrayList