按排序顺序加载android中的联系人

时间:2013-09-24 20:18:59

标签: android cursor android-contacts android-contentresolver

我想将手机中的联系人加载到我的应用中。这段代码完美无缺,除了它不返回排序列表。 e-d Abid 012345678将在列表的顶部,但abid 012345678将在最后。我尝试过不同的Cursor组合(正如你在//评论中看到的那样)。寻找你的指导..

List<ContactInfo> LoadContactListFromPhone()
{

    Cursor cursor = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, null, null, "UPPER(" + ContactsContract.Contacts.DISPLAY_NAME + ") ASC");
    //Cursor cursor = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, ContactsContract.Contacts.HAS_PHONE_NUMBER + " = 1",  null, "UPPER(" + ContactsContract.Contacts.DISPLAY_NAME + ") ASC");
    //Cursor cursor = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI,null, null, null, null); 
    if(cursor.moveToFirst())
    {
        while (cursor.moveToNext()) 
        { 
            String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID)); 
            String hasPhone =  cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
            int hasph = Integer.parseInt(hasPhone);

            if (hasph>-1)
            { 
                Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,   ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = "+ contactId, null, null); 
                if(phones.getCount() > 0)
                {
                    while (phones.moveToNext())
                    { 
                        String phoneNumber = phones.getString(phones.getColumnIndex( ContactsContract.CommonDataKinds.Phone.NUMBER)); 
                        String phonename = phones.getString(phones.getColumnIndex( ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
                        list.add(new ContactInfo(phonename, 0, phoneNumber,0));
                    }
                }
                phones.close(); 
            }
        }
        myList = list;
    }
    else
    {
        Toast.makeText(this, "No Contact Found",Toast.LENGTH_LONG).show();
    }
    cursor.close(); 
    return myList;
}

1 个答案:

答案 0 :(得分:1)

尝试以下代码

Cursor cursor = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, null, null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " COLLATE NOCASE ASC");

它对我来说很好