Introduction
Here I am going to describe how we can fetch all the contacts from our
Android device and display them in a simple ListView. There will be some situations where we need to get all the contacts on our phone. Here I am explaining this in detail. We need to send a query to the contentResolver and this will return a cursor to us. We need to pass a URI to the cursor to get the cursor. The cursor will point to a particular row. We can query like the following to get the contacts from Android.
- cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
This will return the cursor that contains all the contacts on the phone. We need to iterate and get the values by specifying the column name.
For creating the sample application, first create your layout file which will contain a ListView only like the following,
- xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:tools="http://schemas.android.com/tools"
-
- <RelativeLayout>
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:paddingBottom="@dimen/activity_vertical_margin"
- android:paddingLeft="@dimen/activity_horizontal_margin"
- android:paddingRight="@dimen/activity_horizontal_margin"
- android:paddingTop="@dimen/activity_vertical_margin"
- tools:context=".MainActivity">
-
- <ListView
- android:id="@+id/listView"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content" />
- </RelativeLayout>
Now in the java file bind this listview like the following,
- listView = (ListView) findViewById(R.id.listView);
Now get the cursor by querying to the content resolver,
- cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
Here we will get the cursor, now we need to get only whatever the files we needed like contact display name, number, email id, etc.
- String[] from = {ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME, ContactsContract.CommonDataKinds.Phone.NUMBER, ContactsContract.CommonDataKinds.Phone._ID};
Now we need to specify the id of the elements in rows,
- int[] to = {android.R.id.text1, android.R.id.text2};
Now we need to create the list adapter like the following,
- SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_1, cursor, from, to);
Here we are using Android's built in adapter to the listview.
The last step is we need to set this adapter to the listview with setAdapter(),
- listView.setAdapter(adapter);
Now run the app and all your contacts will be shown in the listview of your application.
Please see the screenshots,
.