how to access contacts in my android program

后端 未结 4 432
情歌与酒
情歌与酒 2021-01-31 06:58

I\'m making an text message application and want to access contacts in my Android application .

I want to access contacts as if they where in the actual contact list. W

4条回答
  •  醉话见心
    2021-01-31 07:19

    try this code. this stores all the contacts in the ArrayList

    ArrayList> contactData=new ArrayList>();
    ContentResolver cr = getContentResolver();
     Cursor cursor = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI,null, null, null, null);
     while (cursor.moveToNext()) {
         try{
         String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID)); 
         String name=cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
         String hasPhone = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER)); 
         if (Integer.parseInt(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
             Cursor phones = getContentResolver().query( ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = "+ contactId, null, null);
             while (phones.moveToNext()) { 
                 String phoneNumber = phones.getString(phones.getColumnIndex( ContactsContract.CommonDataKinds.Phone.NUMBER));
                 HashMap map=new HashMap();
                 map.put("name", name);
                 map.put("number", phoneNumber);
                 contactData.add(map);
             } 
             phones.close(); 
         }
     }catch(Exception e){}
     }
    

    if you want to store the specific contact use the if condition.

提交回复
热议问题