How to Get Contact List on Android Programmatically

Jump to Key Sections

Android smartphones have taken over the mobile world and have become an essential part of our lives. They’re not just for calling or texting, but they’re also used for taking pictures, playing games, and keeping in touch with friends and family. With this much usage, it can be challenging to keep track of all the contacts in our phones and keep them organized. This is where the need to get the contact list on Android programmatically arises. By doing so, you’ll be able to export your contacts to a CSV file, create a backup of your contacts, or use it in any other way you need.

This article will guide you on how to get the contact list on Android programmatically using different methods. We’ll also explore some common issues that you may encounter while getting the contact list and how to fix them.

Video Tutorial:

Why You Need to Get Contact List on Android Programmatically

Android smartphones are highly versatile devices, and they enable users to keep in touch with their contacts easily. But have you ever encountered a scenario where you lost all your contacts due to some device malfunctioning or software error? It can be highly frustrating and even detrimental to your personal and professional life. This is where the need to get the contact list on Android programmatically arises.

Getting your contact list programmatically can also help you in various other ways. For instance, you can create backups of your contacts, export them to a CSV file, or use them in any other way you want. This way, you can keep your contacts organized and secure.

Now that we have discussed the importance of getting the contact list on Android programmatically, let’s explore some methods to do so.

Method 1: Using Content Provider

Getting the contact list on Android programmatically can be achieved using a content provider. A content provider is a component that allows access to data in one application from another. In this method, we’ll use the ContactsContract class, which is a content provider to retrieve the contacts from the device.

Before we start, make sure you’ve added the READ_CONTACTS permission in your AndroidManifest.xml file.

1. Create a new class ‘ContactModel’ to store the contact data.
"`
public class ContactModel {
String contactName;
String contactNumber;
public String getContactName() {
return contactName;
}
public void setContactName(String contactName) {
this.contactName = contactName;
}
public String getContactNumber() {
return contactNumber;
}
public void setContactNumber(String contactNumber) {
this.contactNumber = contactNumber;
}
}
"`
2. In your activity’s onCreate method, create an ArrayList of ContactModel to store the contact list.
"`
ArrayList contactList = new ArrayList();
"`
3. Use a Content Resolver to query the ContactsContract class and fetch the contacts.
"`
ContentResolver contentResolver = getContentResolver();
Cursor cursor = contentResolver.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
"`
4. Traverse through the cursor and retrieve the contact name and number.
"`
if (cursor.getCount() > 0) {
while (cursor.moveToNext()) {
String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
if (Integer.parseInt(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
Cursor phoneCursor = contentResolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=?", new String[]{id}, null);
while (phoneCursor.moveToNext()) {
String phoneNumber = phoneCursor.getString(phoneCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
ContactModel contactModel = new ContactModel();
contactModel.setContactName(name);
contactModel.setContactNumber(phoneNumber.trim());
contactList.add(contactModel);
}
phoneCursor.close();
}
}
}
"`
5. You’ll now have the list of all the contacts on your device in the ‘contactList’ ArrayList.

Pros:
– This method is straightforward and easy to implement.
– It’s an official way to fetch contacts from the device.

Cons:
– It may not work efficiently on devices running older versions of Android.

Method 2: Using CursorLoader

The CursorLoader class is part of the Android Support Library and allows you to load data asynchronously from a content provider using a cursor. In this method, we’ll use the CursorLoader class to fetch the contacts from the device.

1. Add the READ_CONTACTS permission in your AndroidManifest.xml file.
2. Create a new class ‘ContactModel’ to store the contact data.
"`
public class ContactModel {
String contactName;
String contactNumber;
public String getContactName() {
return contactName;
}
public void setContactName(String contactName) {
this.contactName = contactName;
}
public String getContactNumber() {
return contactNumber;
}
public void setContactNumber(String contactNumber) {
this.contactNumber = contactNumber;
}
}
"`
3. In your activity’s onCreate method, initialize the LoaderManager to fetch the data.
"`
getLoaderManager().initLoader(1, null, this);
"`
4. Implement the LoaderCallbacks interface to provide callbacks as the data loads.
"`
public class MainActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks {
ArrayList contactList = new ArrayList ();

@Override
public Loader onCreateLoader(int id, Bundle args) {
return new CursorLoader(this,
ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, ContactsContract.Contacts.DISPLAY_NAME +
" ASC
");
}

@Override
public void onLoadFinished(Loader loader, Cursor data) {
while (data.moveToNext()) {
String name = data.getString(data.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumber = data.getString(data.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
ContactModel contactModel = new ContactModel();
contactModel.setContactName(name);
contactModel.setContactNumber(phoneNumber);
contactList.add(contactModel);
}
}

@Override
public void onLoaderReset(Loader loader) {
//Clear the data on loader reset
contactList.clear();
}
}
"`
5. You’ll now have the list of all the contacts on your device in the ‘contactList’ ArrayList.

Pros:
– This method is highly efficient, and the cursor loads the data asynchronously.
– The method uses fewer resources from the device.

Cons:
– This method is slightly complex, and it may take some time to implement.

Method 3: Using SQLiteDatabase

In this method, we’ll use the SQLiteDatabase class to extract the contacts from the system’s SQL database. We’ll create an instance of the SQLiteDatabase class and execute SQL queries to fetch the contacts.

1. Add the READ_CONTACTS permission in your AndroidManifest.xml file.
2. Create a new class ‘ContactModel’ to store the contact data.
"`
public class ContactModel {
String contactName;
String contactNumber;
public String getContactName() {
return contactName;
}
public void setContactName(String contactName) {
this.contactName = contactName;
}
public String getContactNumber() {
return contactNumber;
}
public void setContactNumber(String contactNumber) {
this.contactNumber = contactNumber;
}
}
"`
3. In your activity’s onCreate method, create a new instance of the SQLiteDatabase class.
"`
SQLiteDatabase db = new SQLiteDatabase();
"`
4. Execute the SQL query to fetch contacts from the database.
"`
Cursor cursor = db.rawQuery("SELECT * FROM " + ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null);
if (cursor.getCount() > 0) {
while (cursor.moveToNext()) {
String name = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phone = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DATA1));
ContactModel contactModel = new ContactModel();
contactModel.setContactName(name);
contactModel.setContactNumber(phone);
contactList.add(contactModel);
}
}
"`
5. You’ll now have the list of all the contacts on your device in the ‘contactList’ ArrayList.

Pros:
– This method is efficient and can be used on older versions of Android.

Cons:
– It requires advanced knowledge of SQL queries and may not work efficiently on all devices.

Method 4: Via a Library

Several libraries can help you get the contact list on Android programmatically, making it easier for you to focus on other essential parts of your application.

In this method, we’ll use the ‘Contacts’ library to fetch the contacts from the device.

1. Add the ‘Contacts’ library to your application by adding the following line in your app’s Gradle file.
"`
implementation ‘com.github.tamizhvendan:Contacts:1.1’
"`
2. Create a new class ‘ContactModel’ to store the contact data.
"`
public class ContactModel {
String contactName;
String contactNumber;
public String getContactName() {
return contactName;
}
public void setContactName(String contactName) {
this.contactName = contactName;
}
public String getContactNumber() {
return contactNumber;
}
public void setContactNumber(String contactNumber) {
this.contactNumber = contactNumber;
}
}
"`
3. In your activity’s onCreate method, create a new instance of the ‘Contacts’ library and fetch the contacts.
"`
Contacts.initialize(this);
List contacts = Contacts.getQuery().find();
for (Contact contact : contacts) {
String name = contact.getDisplayName();
String phone = contact.getPhoneNumbers().get(0).getNumber();
ContactModel contactModel = new ContactModel();
contactModel.setContactName(name);
contactModel.setContactNumber(phone);
contactList.add(contactModel);
}
"`
4. You’ll now have the list of all the contacts on your device in the ‘contactList’ ArrayList.

Pros:
– It’s an easy-to-use library, and you don’t have to write any queries.
– It’s highly efficient and can be used on older versions of Android.

Cons:
– The library adds more dependencies to your project.

What to Do If You Can’t Get Contact List on Android Programmatically

Sometimes, you may encounter issues while getting the contact list on Android programmatically. It could be due to several reasons, such as your app not having the necessary permissions, outdated libraries, or even outdated device firmware. Here are some fixes that can help you resolve these issues.

Make sure your app has the READ_CONTACTS permission. If your app doesn’t have the necessary permissions, it may not be able to fetch the contacts. So, make sure you’ve added the READ_CONTACTS permission in your app’s AndroidManifest.xml file.

Update the Contacts library. If you’re using a library to fetch contacts, make sure you’ve updated it to the latest version.

Update your Android firmware. Sometimes, outdated firmware can cause issues with fetching contacts. So, make sure your device firmware is up to date.

Check if the device has any duplicate contacts. Duplicate contacts can also cause issues while fetching contacts on Android. So, check if your device has any duplicate entries and merge them if necessary.

Bonus Tips

1. If you want to export your contact list to a CSV file, you can use the OpenCSV library.
2. You can use the Android’s built-in ‘Share’ functionality to share your contact list with others.
3. You can use a RecyclerView to display the contact list in your app.

FAQs

Q1: What should I do if I can’t fetch some contacts?

A: This could be due to the contact having custom fields or tags that your application doesn’t support. To fetch these contacts, you’ll have to use a custom query.

Q2: How can I create a backup of my contact list?

A: You can create a backup of your contact list by exporting it to a CSV file.

Q3: How can I sort the contact list?

A: You can sort the contact list using the ‘ORDER BY’ clause in your SQL query.

Q4: Can I fetch contacts from a specific account?

A: Yes, you can fetch contacts from a specific account by using the ‘ACCOUNT_NAME’ and ‘ACCOUNT_TYPE’ fields in your query.

Q5: How can I add a new contact programmatically?

A: You can add a new contact programmatically by using the ContactsContract.Data class and insert a new row with the ‘MIME_TYPE’ set to ‘CONTACTS’.

Final Thoughts

In this article, we’ve explored various methods to get the contact list on Android programmatically, along with some bonus tips and FAQs. You can use any of these methods to fetch the contact list in your app and use it in any other way you want. If you’re having issues getting the contact list, make sure you’ve added the READ_CONTACTS permission and have updated any libraries you may be using. With this information, you’ll be able to keep your contacts organized and secure, which will be highly beneficial to your personal and professional life.