How to Get Saved Contacts in Android Application using Cursor?
Phone Contacts are very important source of data for everyone and hence accessing phone contacts is the main feature for many applications like Truecaller to help their users and provide them a better experience. We all have a default application in our mobile to manage contacts but what happens if we will create our own application that will read all the saved contacts and will show them to the user. We can use that application for backup of our contacts. So, in this article, we are going to learn how to develop an application that will read contacts.
Note: A Cursor is a class that contains the result set for a particular query that was made against a database in Android. This class has an API that provides a facility to read the columns which were returned from the query, as well as helps to iterate over the rows of the result set.Want a more fast-paced & competitive environment to learn the fundamentals of Android?Click here to head to a guide uniquely curated by our experts with the aim to make you industry ready in no time!
What we are going to build in this article?
We will be building a simple application in which we will be displaying a Button and when we will click on that button, and it will add all saved contacts (their names and numbers) into ListView of our application. Note that we have to give permission to our application to read our phone contacts. We will use Java language for developing this project.
Step by Step Implementation
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.
Step 2: Add Permission
Now, navigate to the app> manifests> AndroidManifest.xml file and add below permission there to read contacts.
Step 3: Working with the activity_main.xml file
Now it’s time to design the layout of the application. So, navigate to app > res > layout > activity_main.xml and paste the below-written code in the activity_main.xml file.
Step 4: Working with the MainActivity.java file
Navigate to the app > java > package name > MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.
Congratulation, now our application is ready so click on the run button. Here is the output video of the application.