Android get all contacts telephone number in ArrayList

后端 未结 6 1193
礼貌的吻别
礼貌的吻别 2020-12-02 20:40

I am trying to save all contacts telephone numbers in an ArrayList but I cant find a way how. Is there a way to get them instead of picking them one by one with ContactsCont

6条回答
  •  -上瘾入骨i
    2020-12-02 21:11

    This method is optimized as well as fetch only distinct contacts

    @RequiresApi(api = Build.VERSION_CODES.N)
    private List getContacts() {
    
        ArrayList list = new ArrayList<>();
        Cursor cursor = this.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
    
        cursor.moveToFirst();
    
        while (cursor.moveToNext()) {
    
            list.add(new ModelContacts(cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME))
                    , cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER))));
    
        }
        cursor.close();
    
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
    
            List distinctList = list.stream().filter(distinctByKey(c -> c.getName()))
                    .collect(Collectors.toList());
            
            return distinctList;
        }
        else {
           
            return list;
        }
    }
    
    @RequiresApi(api = Build.VERSION_CODES.N)
    public static  Predicate distinctByKey (final Function keyExtractor)
    {
        Map map = new ConcurrentHashMap<>();
        return t -> map.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
    }
    

提交回复
热议问题