【问题标题】:Sorting Contacts in Android在 Android 中对联系人进行排序
【发布时间】:2014-10-18 19:36:04
【问题描述】:
    public void ReadContacts() {
    Cursor people = getContentResolver().query(Phone.CONTENT_URI, null, null, null,Phone.DISPLAY_NAME + " ASC ");
    int indexName = people
            .getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
    int indexNumber = people
            .getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);

    people.moveToFirst();
    do {
        name = people.getString(indexName);
        number = people.getString(indexNumber);

        contacts.put(name, number);

    } while (people.moveToNext());

    printHashMap(contacts);

}

public void printHashMap(HashMap<String, String> a) {

    for (Entry<String, String> lists : a.entrySet()) {
        Log.d(lists.getKey(), lists.getValue());
    }

}

尽管使用了 ASC,但联系人没有排序?你能帮我找出原因吗? 我也使用了 upper() 方法

光标 cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, "upper("+ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + ") ASC");

【问题讨论】:

    标签: android sorting contacts


    【解决方案1】:

    您将(排序的)结果放在不保留元素顺序的 HashMap 中。使用 List 就可以了。

    编辑:使用您在评论中建议的Tuple 类,它应该如下所示:

    static class Tuple {
        public String name;
        public String number;
    
        public Tuple(String name, String number) {
            this.name = name;
            this.number = number;
        }
    }
    
    public void ReadContacts() {
        Cursor people = getContentResolver().query(Phone.CONTENT_URI, null,  null, null, Phone.DISPLAY_NAME + " ASC ");
        int indexName = people
                .getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
        int indexNumber = people
                .getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
    
        List<Tuple> contacts = new ArrayList<Tuple>();
    
        people.moveToFirst();
        do {
            name = people.getString(indexName);
            number = people.getString(indexNumber);
    
            contacts.add(new Tuple(name, number));
    
        } while (people.moveToNext());
    
        printHashMap(contacts);
    
    }
    
    public void printList(List<Tuple> list) {
    
        for (Tuple tuple : list) {
            Log.d(tuple.name + ", " + tuple.number);
        }
    }
    

    但在这种情况下,我建议将 Tuple 类重命名为 Contact。拥有一个包含名为“name”和“number”的成员的元组类很奇怪。

    【讨论】:

    • 没有 ArrayList 之类的东西吗?
    • 我必须使用两个不同的数组列表?
    • 最好使用成对列表。 developer.android.com/reference/android/util/Pair.html 像这样: List> myList = new ArrayList>();
    • 类元组 { String x;字符串 y; } List list = new ArrayList();如果我这样做,那么如何在 x,y 中添加相应的值
    • 在 Tuple 类中使用构造函数。我已经更新了我的答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多