【问题标题】:android get all contactsandroid获取所有联系人
【发布时间】:2012-09-15 17:49:38
【问题描述】:

如何在我的 Android 中获取所有联系人的姓名并将它们放入字符串数组中?

【问题讨论】:

标签: android


【解决方案1】:

也试试这个,

private void getContactList() {
    ContentResolver cr = getContentResolver();
    Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
            null, null, null, null);

    if ((cur != null ? cur.getCount() : 0) > 0) {
        while (cur != null && cur.moveToNext()) {
            String id = cur.getString(
                    cur.getColumnIndex(ContactsContract.Contacts._ID));
            String name = cur.getString(cur.getColumnIndex(
                    ContactsContract.Contacts.DISPLAY_NAME));

            if (cur.getInt(cur.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 phoneNo = pCur.getString(pCur.getColumnIndex(
                            ContactsContract.CommonDataKinds.Phone.NUMBER));
                    Log.i(TAG, "Name: " + name);
                    Log.i(TAG, "Phone Number: " + phoneNo);
                }
                pCur.close();
            }
        }
    }
    if(cur!=null){
        cur.close();
    }
}

如果您需要更多参考方式,请参考此链接Read ContactList

【讨论】:

  • 由于某种原因,此代码将每个联系人获取两次。你知道为什么吗?
  • @Aerrow 有时会得到一些联系人两次。你解决了这个问题吗?
  • 不要忘记关闭光标!
  • 请勿使用此代码。它查询所有联系人,然后对每个联系人执行附加查询。糟糕的性能 - 在真实设备上运行可能需要 10 多秒。
  • @Vasiliy 是对的,如果您的联系人较少,您可能会被欺骗它很快,但对于拥有大量联系人的实际用户来说是个问题。
【解决方案2】:

获取联系人信息、照片联系人、照片 uri 并转换为 Class 模型

1)。类模型示例:

    public class ContactModel {
        public String id;
        public String name;
        public String mobileNumber;
        public Bitmap photo;
        public Uri photoURI;
    }

2)。获取联系人并转换为模型

     public List<ContactModel> getContacts(Context ctx) {
        List<ContactModel> list = new ArrayList<>();
        ContentResolver contentResolver = ctx.getContentResolver();
        Cursor cursor = contentResolver.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
        if (cursor.getCount() > 0) {
            while (cursor.moveToNext()) {
                String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
                if (cursor.getInt(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER)) > 0) {
                    Cursor cursorInfo = contentResolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
                            ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[]{id}, null);
                    InputStream inputStream = ContactsContract.Contacts.openContactPhotoInputStream(ctx.getContentResolver(),
                            ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, new Long(id)));

                    Uri person = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, new Long(id));
                    Uri pURI = Uri.withAppendedPath(person, ContactsContract.Contacts.Photo.CONTENT_DIRECTORY);

                    Bitmap photo = null;
                    if (inputStream != null) {
                        photo = BitmapFactory.decodeStream(inputStream);
                    }
                    while (cursorInfo.moveToNext()) {
                        ContactModel info = new ContactModel();
                        info.id = id;
                        info.name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
                        info.mobileNumber = cursorInfo.getString(cursorInfo.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                        info.photo = photo;
                        info.photoURI= pURI;
                        list.add(info);
                    }

                    cursorInfo.close();
                }
            }
            cursor.close();
        }
        return list;
    }

【讨论】:

  • 很棒的功能,只需要在完成第一个while子句后再添加一行来关闭光标。非常感谢
  • 存储所有位图可能是个坏主意,例如您加载 1000 个位图,而用户只能看到前 10 个。
【解决方案3】:
public class MyActivity extends Activity 
                        implements LoaderManager.LoaderCallbacks<Cursor> {

    private static final int CONTACTS_LOADER_ID = 1;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        // Prepare the loader.  Either re-connect with an existing one,
        // or start a new one.
        getLoaderManager().initLoader(CONTACTS_LOADER_ID,
                                      null,
                                      this);
    }

    @Override
    public Loader<Cursor> onCreateLoader(int id, Bundle args) {
        // This is called when a new Loader needs to be created.

        if (id == CONTACTS_LOADER_ID) {
            return contactsLoader();
        }
        return null;
    }

    @Override
    public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
        //The framework will take care of closing the
        // old cursor once we return.
        List<String> contacts = contactsFromCursor(cursor);
    }

    @Override
    public void onLoaderReset(Loader<Cursor> loader) {
        // This is called when the last Cursor provided to onLoadFinished()
        // above is about to be closed.  We need to make sure we are no
        // longer using it.
    }

    private  Loader<Cursor> contactsLoader() {
        Uri contactsUri = ContactsContract.Contacts.CONTENT_URI; // The content URI of the phone contacts

        String[] projection = {                                  // The columns to return for each row
                ContactsContract.Contacts.DISPLAY_NAME
        } ;

        String selection = null;                                 //Selection criteria
        String[] selectionArgs = {};                             //Selection criteria
        String sortOrder = null;                                 //The sort order for the returned rows

        return new CursorLoader(
                getApplicationContext(),
                contactsUri,
                projection,
                selection,
                selectionArgs,
                sortOrder);
    }

    private List<String> contactsFromCursor(Cursor cursor) {
        List<String> contacts = new ArrayList<String>();

        if (cursor.getCount() > 0) {
            cursor.moveToFirst();

            do {
                String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
                contacts.add(name);
            } while (cursor.moveToNext());
        }

        return contacts;
    }

}

别忘了

<uses-permission android:name="android.permission.READ_CONTACTS" />

【讨论】:

  • 很好地使用 CursorLoader。你知道如何从 CursorLoader 中的每个联系人中提取电话号码吗?
  • 您可以实现 LoaderManager.LoaderCallbacks 而不是 LoaderManager.LoaderCallbacks。其中“联系人”是您的自定义实体。
  • @Artyom 你能解释一下如何获取电话号码部分吗?
【解决方案4】:

在不到一秒钟的时间内获取所有联系人,并且不会对您的活动造成任何负担。 跟随我的步骤就像魅力一样。

ArrayList<Contact> contactList = new ArrayList<>();

private static final String[] PROJECTION = new String[]{
        ContactsContract.CommonDataKinds.Phone.CONTACT_ID,
        ContactsContract.Contacts.DISPLAY_NAME,
        ContactsContract.CommonDataKinds.Phone.NUMBER
};

private void getContactList() {
    ContentResolver cr = getContentResolver();

    Cursor cursor = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, PROJECTION, null, null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC");
    if (cursor != null) {
        HashSet<String> mobileNoSet = new HashSet<String>();
        try {
            final int nameIndex = cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
            final int numberIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);

            String name, number;
            while (cursor.moveToNext()) {
                name = cursor.getString(nameIndex);
                number = cursor.getString(numberIndex);
                number = number.replace(" ", "");
                if (!mobileNoSet.contains(number)) {
                    contactList.add(new Contact(name, number));
                    mobileNoSet.add(number);
                    Log.d("hvy", "onCreaterrView  Phone Number: name = " + name
                            + " No = " + number);
                }
            }
        } finally {
            cursor.close();
        }
    }
}

联系人


public class Contact {
public String name;
public String phoneNumber;

public Contact() {
}

public Contact(String name, String phoneNumber ) {
    this.name = name;
    this.phoneNumber = phoneNumber;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getPhoneNumber() {
    return phoneNumber;
}

public void setPhoneNumber(String phoneNumber) {
    this.phoneNumber = phoneNumber;
}

}

好处

  • 不到一秒
  • 无负载
  • 升序
  • 没有重复的联系人

【讨论】:

  • 这应该是被接受的答案。因为它太快了。谢谢
  • 这非常好。需要提到的一个关键点是,这里的最大区别在于,此优化解决方案使用的 uri 是 ContactsContract.CommonDataKinds.Phone.CONTENT_URI,这使您可以直接访问 ContactsContract.CommonDataKinds.Phone.NUMBER 列。在更糟糕的答案中,您查询 uri ContactsContract.Contacts.CONTENT_URI,它不会让您访问 ContactsContract.CommonDataKinds.Phone.NUMBER 列,因此您必须使用每个联系人的 id 运行另一个查询才能访问它。
【解决方案5】:

改进@Adiii 的答案 - 它将清理电话号码并删除所有重复项

声明一个全局变量

// Hash Maps
Map<String, String> namePhoneMap = new HashMap<String, String>();

然后使用下面的函数

private void getPhoneNumbers() {

        Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);

        // Loop Through All The Numbers
        while (phones.moveToNext()) {

            String name = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
            String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));

            // Cleanup the phone number
            phoneNumber = phoneNumber.replaceAll("[()\\s-]+", "");

            // Enter Into Hash Map
            namePhoneMap.put(phoneNumber, name);

        }

        // Get The Contents of Hash Map in Log
        for (Map.Entry<String, String> entry : namePhoneMap.entrySet()) {
            String key = entry.getKey();
            Log.d(TAG, "Phone :" + key);
            String value = entry.getValue();
            Log.d(TAG, "Name :" + value);
        }

        phones.close();

    }

请记住,在上面的示例中,键是电话号码,值是名称,因此请阅读您的内容,例如 998xxxxx282->Mahatma Gandhi 而不是 Mahatma Gandhi->998xxxxx282

【讨论】:

    【解决方案6】:
    Cursor contacts = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
    String aNameFromContacts[] = new String[contacts.getCount()];  
    String aNumberFromContacts[] = new String[contacts.getCount()];  
    int i = 0;
    
    int nameFieldColumnIndex = contacts.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
    int numberFieldColumnIndex = contacts.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
    
    while(contacts.moveToNext()) {
    
        String contactName = contacts.getString(nameFieldColumnIndex);
        aNameFromContacts[i] =    contactName ; 
    
        String number = contacts.getString(numberFieldColumnIndex);
        aNumberFromContacts[i] =    number ;
    i++;
    }
    
    contacts.close();
    

    结果将是一个包含联系人的NameFromContacts 数组。还要确保你已经添加了

    <uses-permission android:name="android.permission.READ_CONTACTS" />
    

    在 main.xml 中

    【讨论】:

    • 非常感谢,我会试试的,如果我有其他问题,我会问你
    • 感谢帮助,如何在 ListView 中显示所有姓名?(我可以在另一个窗口中看到我手机中的所有联系人姓名)?谢谢
    • 这个答案是错误的。 PhoneLookup.NUMBER 不是 ContactsContract.Contacts.CONTENT_URI 中的列,numberFieldColumnIndex 总是返回 -1
    • 应该是这样的:Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null, null); while (phones.moveToNext()) { String name=phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Pho‌​ne.DISPLAY_NAME)); String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NU‌​MBER)); } phones.close();
    • @gunner_dev 如果你确定这个答案包括你的编辑会起作用,请写一个新的答案。
    【解决方案7】:

    这是获取联系人列表名称和号码的方法

     private void getAllContacts() {
        ContentResolver contentResolver = getContentResolver();
        Cursor cursor = contentResolver.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC");
        if (cursor.getCount() > 0) {
            while (cursor.moveToNext()) {
    
                int hasPhoneNumber = Integer.parseInt(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER)));
                if (hasPhoneNumber > 0) {
                    String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
                    String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
                    Cursor phoneCursor = contentResolver.query(
                            ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                            null,
                            ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[]{id},
                            null);
                    if (phoneCursor != null) {
                        if (phoneCursor.moveToNext()) {
                            String phoneNumber = phoneCursor.getString(phoneCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
    
       //At here You can add phoneNUmber and Name to you listView ,ModelClass,Recyclerview
                            phoneCursor.close();
                        }
    
    
                    }
                }
            }
        }
    }
    

    【讨论】:

      【解决方案8】:
      //GET CONTACTLIST WITH ALL FIELD...       
      
      public ArrayList < ContactItem > getReadContacts() {
               ArrayList < ContactItem > contactList = new ArrayList < > ();
               ContentResolver cr = getContentResolver();
               Cursor mainCursor = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
               if (mainCursor != null) {
                while (mainCursor.moveToNext()) {
                 ContactItem contactItem = new ContactItem();
                 String id = mainCursor.getString(mainCursor.getColumnIndex(ContactsContract.Contacts._ID));
                 String displayName = mainCursor.getString(mainCursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
      
                 Uri contactUri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, Long.parseLong(id));
                 Uri displayPhotoUri = Uri.withAppendedPath(contactUri, ContactsContract.Contacts.Photo.DISPLAY_PHOTO);
      
                 //ADD NAME AND CONTACT PHOTO DATA...
                 contactItem.setDisplayName(displayName);
                 contactItem.setPhotoUrl(displayPhotoUri.toString());
      
                 if (Integer.parseInt(mainCursor.getString(mainCursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
                  //ADD PHONE DATA...
                  ArrayList < PhoneContact > arrayListPhone = new ArrayList < > ();
                  Cursor phoneCursor = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[] {
                   id
                  }, null);
                  if (phoneCursor != null) {
                   while (phoneCursor.moveToNext()) {
                    PhoneContact phoneContact = new PhoneContact();
                    String phone = phoneCursor.getString(phoneCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                    phoneContact.setPhone(phone);
                    arrayListPhone.add(phoneContact);
                   }
                  }
                  if (phoneCursor != null) {
                   phoneCursor.close();
                  }
                  contactItem.setArrayListPhone(arrayListPhone);
      
      
                  //ADD E-MAIL DATA...
                  ArrayList < EmailContact > arrayListEmail = new ArrayList < > ();
                  Cursor emailCursor = cr.query(ContactsContract.CommonDataKinds.Email.CONTENT_URI, null, ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?", new String[] {
                   id
                  }, null);
                  if (emailCursor != null) {
                   while (emailCursor.moveToNext()) {
                    EmailContact emailContact = new EmailContact();
                    String email = emailCursor.getString(emailCursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
                    emailContact.setEmail(email);
                    arrayListEmail.add(emailContact);
                   }
                  }
                  if (emailCursor != null) {
                   emailCursor.close();
                  }
                  contactItem.setArrayListEmail(arrayListEmail);
      
                  //ADD ADDRESS DATA...
                  ArrayList < PostalAddress > arrayListAddress = new ArrayList < > ();
                  Cursor addrCursor = getContentResolver().query(ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_URI, null, ContactsContract.CommonDataKinds.StructuredPostal.CONTACT_ID + " = ?", new String[] {
                   id
                  }, null);
                  if (addrCursor != null) {
                   while (addrCursor.moveToNext()) {
                    PostalAddress postalAddress = new PostalAddress();
                    String city = addrCursor.getString(addrCursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.CITY));
                    String state = addrCursor.getString(addrCursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.REGION));
                    String country = addrCursor.getString(addrCursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.COUNTRY));
                    postalAddress.setCity(city);
                    postalAddress.setState(state);
                    postalAddress.setCountry(country);
                    arrayListAddress.add(postalAddress);
                   }
                  }
                  if (addrCursor != null) {
                   addrCursor.close();
                  }
                  contactItem.setArrayListAddress(arrayListAddress);
                 }
                 contactList.add(contactItem);
                }
               }
               if (mainCursor != null) {
                mainCursor.close();
               }
               return contactList;
              }
      
      
      
          //MODEL...
              public class ContactItem {
      
                  private String displayName;
                  private String photoUrl;
                  private ArrayList<PhoneContact> arrayListPhone = new ArrayList<>();
                  private ArrayList<EmailContact> arrayListEmail = new ArrayList<>();
                  private ArrayList<PostalAddress> arrayListAddress = new ArrayList<>();
      
      
                  public String getDisplayName() {
                      return displayName;
                  }
      
                  public void setDisplayName(String displayName) {
                      this.displayName = displayName;
                  }
      
                  public String getPhotoUrl() {
                      return photoUrl;
                  }
      
                  public void setPhotoUrl(String photoUrl) {
                      this.photoUrl = photoUrl;
                  }
      
                  public ArrayList<PhoneContact> getArrayListPhone() {
                      return arrayListPhone;
                  }
      
                  public void setArrayListPhone(ArrayList<PhoneContact> arrayListPhone) {
                      this.arrayListPhone = arrayListPhone;
                  }
      
                  public ArrayList<EmailContact> getArrayListEmail() {
                      return arrayListEmail;
                  }
      
                  public void setArrayListEmail(ArrayList<EmailContact> arrayListEmail) {
                      this.arrayListEmail = arrayListEmail;
                  }
      
                  public ArrayList<PostalAddress> getArrayListAddress() {
                      return arrayListAddress;
                  }
      
                  public void setArrayListAddress(ArrayList<PostalAddress> arrayListAddress) {
                      this.arrayListAddress = arrayListAddress;
                  }
              }
      
              public class EmailContact
              {
                  private String email = "";
      
                  public String getEmail() {
                      return email;
                  }
      
                  public void setEmail(String email) {
                      this.email = email;
                  }
              }
      
              public class PhoneContact
              {
                  private String phone="";
      
                  public String getPhone()
                  {
                      return phone;
                  }
      
                  public void setPhone(String phone) {
                      this.phone = phone;
                  }
              }
      
      
              public class PostalAddress
              {
                  private String city="";
                  private String state="";
                  private String country="";
      
                  public String getCity() {
                      return city;
                  }
      
                  public void setCity(String city) {
                      this.city = city;
                  }
      
                  public String getState() {
                      return state;
                  }
      
                  public void setState(String state) {
                      this.state = state;
                  }
      
                  public String getCountry() {
                      return country;
                  }
      
                  public void setCountry(String country) {
                      this.country = country;
                  }
              }
      

      【讨论】:

        【解决方案9】:
        //In Kotlin     
        private fun showContacts() {
                // Check the SDK version and whether the permission is already granted or not.
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && checkSelfPermission(
                        requireContext(),
                        Manifest.permission.READ_CONTACTS
                    ) != PackageManager.PERMISSION_GRANTED
                ) {
                    requestPermissions(
                        arrayOf(Manifest.permission.READ_CONTACTS),
                        1001
                    )
                    //After this point you wait for callback in onRequestPermissionsResult(int, String[], int[]) overriden method
                } else {
                    // Android version is lesser than 6.0 or the permission is already granted.
                    getContactList()
                }
            }
            private fun getContactList() {
                val cr: ContentResolver = requireActivity().contentResolver
                val cur: Cursor? = cr.query(
                    ContactsContract.Contacts.CONTENT_URI,
                    null, null, null, null
                )
                if ((if (cur != null) cur.getCount() else 0) > 0) {
                    while (cur != null && cur.moveToNext()) {
                        val id: String = cur.getString(
                            cur.getColumnIndex(ContactsContract.Contacts._ID)
                        )
                        val name: String = cur.getString(
                            cur.getColumnIndex(
                                ContactsContract.Contacts.DISPLAY_NAME
                            )
                        )
                        if (cur.getInt(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER)) > 0) {
                            val pCur: Cursor? = cr.query(
                                ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                                null,
                                ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
                                arrayOf(id),
                                null
                            )
                            pCur?.let {
                                while (pCur.moveToNext()) {
                                    val phoneNo: String = pCur.getString(
                                        pCur.getColumnIndex(
                                            ContactsContract.CommonDataKinds.Phone.NUMBER
                                        )
                                    )
                                    Timber.i("Name: $name")
                                    Timber.i("Phone Number: $phoneNo")
                                }
                                pCur.close()
                            }
        
                        }
                    }
                }
                if (cur != null) {
                    cur.close()
                }
            }
        

        【讨论】:

          【解决方案10】:

          我正在使用这种方法,并且效果很好。 它得到收藏、图片、姓名、号码等(联系人的所有详细信息)。而且它不是重复的。

          列表

          private static List<FavContact> contactList = new ArrayList<>();
          

          获取联系人的方法

          @SuppressLint("Range")
          public static void readContacts(Context context) {
          
              if (context == null)
                  return;
          
              ContentResolver contentResolver = context.getContentResolver();
          
              if (contentResolver == null)
                  return;
          
              String[] fieldListProjection = {
                      ContactsContract.CommonDataKinds.Phone.CONTACT_ID,
                      ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME_PRIMARY,
                      ContactsContract.CommonDataKinds.Phone.NUMBER,
                      ContactsContract.CommonDataKinds.Phone.NORMALIZED_NUMBER,
                      ContactsContract.Contacts.HAS_PHONE_NUMBER,
                      ContactsContract.Contacts.PHOTO_URI
                      ,ContactsContract.Contacts.STARRED
              };
              String sort = ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME_PRIMARY + " ASC";
              Cursor phones = contentResolver
                      .query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI
                              , fieldListProjection, null, null, sort);
              HashSet<String> normalizedNumbersAlreadyFound = new HashSet<>();
          
              if (phones != null && phones.getCount() > 0) {
                  while (phones.moveToNext()) {
                      String normalizedNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
          
                      if (Integer.parseInt(phones.getString(phones.getColumnIndex(
                              ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
                          if (normalizedNumbersAlreadyFound.add(normalizedNumber)) {
          
                              int id = phones.getInt(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID));
                              String name = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
                              String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                              int fav = phones.getInt(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.STARRED));
                              boolean isFav;
                              isFav= fav == 1;
          
                              String uri = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.PHOTO_URI));
                              if(uri!=null){
                                  contactList.add(new FavContact(id,isFav,uri,name,phoneNumber));
                              }
                              else{
                                  contactList.add(new FavContact(id,isFav,name,phoneNumber));
                              }
          
                          }
                      }
                  }
                  phones.close();
              }
          }
          

          模型类

          public class FavContact{
          
              private int id;
          
              private boolean isFavorite;
          
              private String image;
          
              private String name;
          
              private String number;
             
          
              public FavContact(int id,boolean isFavorite, String image, String name, String number){
                  this.id=id;
                  this.isFavorite = isFavorite;
                  this.image = image;
                  this.name = name;
                  this.number = number;
              }
          
              public FavContact(int id,boolean isFavorite, String name, String number){
                  this.id=id;
                  this.isFavorite = isFavorite;
                  this.name = name;
                  this.number = number;
              }
          
              public int getId() {
                  return id;
              }
          
              public void setId(int id) {
                  this.id = id;
              }
          
              public boolean isFavorite() {
                  return isFavorite;
              }
          
              public void setFavorite(boolean favorite) {
                  isFavorite = favorite;
              }
          
              public String getImage() {
                  return image;
              }
          
              public void setImage(String image) {
                  this.image = image;
              }
          
              public String getName() {
                  return name;
              }
          
              public void setName(String name) {
                  this.name = name;
              }
          
              public String getNumber() {
                  return number;
              }
          
              public void setNumber(String number) {
                  this.number = number;
              }
          
          }
          

          适配器

          public class ContactAdapter extends RecyclerView.Adapter<ContactAdapter.MyViewHolder> implements Filterable {
          
          private final Context context;
          private final List<FavContact> contactList;
          private final List<FavContact> filterList;
          private final OnMyOwnClickListener onMyOwnClickListener;
          private final FavContactRepo favContactRepo;
          
          public ContactAdapter(Application application,Context context, List<FavContact> contactList, OnMyOwnClickListener onMyOwnClickListener) {
              this.context = context;
              this.contactList = contactList;
              this.onMyOwnClickListener = onMyOwnClickListener;
              filterList = new ArrayList<>(contactList);
              favContactRepo = new FavContactRepo(application);
          }
          
          @NonNull
          @Override
          public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
              final LayoutInflater inflater = LayoutInflater.from(context);
              @SuppressLint("InflateParams") final View view = inflater.inflate(R.layout.design_fav_contact, null, false);
              return new MyViewHolder(view,onMyOwnClickListener);
          }
          
          @Override
          public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
              final FavContact obj = contactList.get(position);
              holder.tv_contact_name.setText(obj.getName());
          
              holder.tv_contact_number.setText(obj.getNumber());
          
              if(obj.getImage()==null){
                  Picasso.get().load(R.drawable.ic_circle_fav_no_dp).fit().into(holder.img_contact);
              }
              else{
                  Bitmap bp;
                  try {
                      bp = MediaStore.Images.Media
                              .getBitmap(context.getContentResolver(),
                                      Uri.parse(obj.getImage()));
                      Glide.with(context).load(bp).centerInside().into(holder.img_contact);
                  } catch (IOException e) {
                      e.printStackTrace();
                      Picasso.get().load(R.drawable.ic_circle_fav_no_dp).fit().into(holder.img_contact);
                  }
          
              }
              obj.setFavorite(favContactRepo.checkIfFavourite(obj.getId()));
          
              if(obj.isFavorite()){
                  Picasso.get().load(R.drawable.ic_menu_favorite_true).into(holder.img_fav_true_or_not);
              }
              else{
                  Picasso.get().load(R.drawable.ic_menu_favorite_false).into(holder.img_fav_true_or_not);
              }
          
          }
          
          @Override
          public int getItemCount() {
              return contactList.size();
          }
          
          @Override
          public long getItemId(int position) {
              return position;
          }
          @Override
          public int getItemViewType(int position) {
              return position;
          }
          
          static class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
              CircleImageView img_contact;
              TextView tv_contact_name,tv_contact_number;
              ImageView img_fav_true_or_not;
              ImageView img_call;
              RecyclerView fav_contact_rv;
          
              OnMyOwnClickListener onMyOwnClickListener;
              public MyViewHolder(@NonNull View itemView, OnMyOwnClickListener onMyOwnClickListener) {
                  super(itemView);
                  img_contact = itemView.findViewById(R.id.img_contact);
                  tv_contact_name = itemView.findViewById(R.id.tv_contact_name);
                  img_fav_true_or_not = itemView.findViewById(R.id.img_fav_true_or_not);
                  tv_contact_number = itemView.findViewById(R.id.tv_contact_number);
                  img_call = itemView.findViewById(R.id.img_call);
                  fav_contact_rv = itemView.findViewById(R.id.fav_contact_rv);
          
                  this.onMyOwnClickListener = onMyOwnClickListener;
                  img_call.setOnClickListener(this);
                  img_fav_true_or_not.setOnClickListener(this);
                  img_contact.setOnClickListener(this);
                  itemView.setOnClickListener(this);
              }
          
              @Override
              public void onClick(View view) {
                  onMyOwnClickListener.onMyOwnClick(getAbsoluteAdapterPosition(),view);
              }
          }
          
          public interface OnMyOwnClickListener{
              void onMyOwnClick(int position,View view);
          }
          
          
          @Override
          public Filter getFilter() {
              return filteredList;
          }
          
          public Filter filteredList = new Filter() {
              @Override
              protected FilterResults performFiltering(CharSequence constraint) {
                  List<FavContact> filteredList = new ArrayList<>();
                  if (constraint == null || constraint.length() == 0) {
                      filteredList=filterList;
                  } else {
                      String filterText = constraint.toString().toLowerCase().trim();
                      for (FavContact item : filterList) {
                          if (item.getName().toLowerCase().contains(filterText)
                                  ||item.getNumber().toLowerCase().contains(filterText)) {
                              filteredList.add(item);
                          }
                      }
          
                  }
          
                  FilterResults results = new FilterResults();
                  results.values = filteredList;
          
                  return results;
              }
          
              @SuppressLint("NotifyDataSetChanged")
              @Override
              protected void publishResults(CharSequence constraint, FilterResults results) {
                  contactList.clear();
                  contactList.addAll((ArrayList)results.values);
                  notifyDataSetChanged();
          
              }
          };
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2017-02-22
            • 2015-05-23
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2011-05-19
            • 1970-01-01
            相关资源
            最近更新 更多