Skip to content

Instantly share code, notes, and snippets.

@xvarlez
Last active February 17, 2016 10:27
Show Gist options
  • Select an option

  • Save xvarlez/43c449eeb5c27180f90a to your computer and use it in GitHub Desktop.

Select an option

Save xvarlez/43c449eeb5c27180f90a to your computer and use it in GitHub Desktop.
Android contacts cache
/**
* Cache for addressbook contacts.
*/
public class ContactsCache {
private static class Holder {
static final ContactsCache INSTANCE = new ContactsCache();
}
/**
* The activity context.
*/
private Context mContext;
/**
* Contacts table.
*/
private SparseArray<Contact> mContactsTable;
/**
* Contacts list.
*/
private List<Contact> mContactsList;
public ContactsCache() {
}
public static ContactsCache getInstance() {
return Holder.INSTANCE;
}
/**
* Sets the context.
* @param context
*/
public void init(Context context) {
this.mContext = context;
}
/**
* Get a particular contact.
* @param contactId The addressbook id of the contact.
* @return The Contact or null if not found
*/
public Contact getContact(int contactId) {
return getContactsTable().get(contactId);
}
/**
* Gets the contacts list.
* @return
*/
public List<Contact> getContactsList() {
if(mContactsList == null) {
mContactsList = new ArrayList<>(getContactsTable().size());
for(int i = 0; i < getContactsTable().size(); i++) {
mContactsList.add(getContactsTable().valueAt(i));
}
Collections.sort(mContactsList);
}
return mContactsList;
}
/**
* Gets the contacts table.
* @return
*/
private SparseArray<Contact> getContactsTable() {
if(mContactsTable == null) {
mContactsTable = loadContactsFromAddressBook();
}
return mContactsTable;
}
/**
* Loads the contacts contained in the phone address book.
* @return
*/
protected SparseArray<Contact> loadContactsFromAddressBook() {
SparseArray<Contact> contactsTable = new SparseArray<>();
Cursor phones = mContext.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
if(phones != null) {
while (phones.moveToNext()) {
int id = phones.getInt(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone._ID));
String name = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
int phoneType = phones.getInt(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE));
int phoneTypeStringRes = ContactsContract.CommonDataKinds.Phone.getTypeLabelResource(phoneType);
Contact tmpContact = new Contact(String.valueOf(id), name, phoneNumber, mContext.getString(phoneTypeStringRes));
contactsTable.put(id, tmpContact);
}
phones.close();
}
return contactsTable;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment