Content User Example

This example shows how to use built-in content providers. There are only two significant files - the activity ContentUserDemo and the layout file (less significant).

Notice the reference to the built-in Peope content provider. It provides us with the list of people in our address book.

package org.example.cp;

import java.util.ArrayList;

import android.content.ContentResolver;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.Contacts.People;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class ContentUserDemo extends Activity {
    private static final String TAG = "ContentUserDemo";
    private ArrayList<String> list;

    /** Called when the activity is first created. */
    public void onCreate(Bundle savedInstanceState) {

        // Get content provider and cursor
        ContentResolver r = getContentResolver();
        Cursor cursor = r.query(People.CONTENT_URI, null, null, null, null);

        // Let activity manage the cursor
        Log.d(TAG, "cursor.getCount()=" + cursor.getCount());

        // Get value from content provider
        int nameIndex = cursor.getColumnIndexOrThrow(People.NAME);
        int numberIndex = cursor.getColumnIndexOrThrow(People.NUMBER);

        list = new ArrayList<String>();
        do {
            String name = cursor.getString(nameIndex);
            String number = cursor.getString(numberIndex);
            list.add(name + ": " + number);
        } while (cursor.moveToNext());

        // Get the list view
        ListView listView = (ListView) findViewById(;
        ArrayAdapter<String> aa = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, list);



This layout just dumps the data in a ListView. One interesting part is linking the ArrayAdapter to the ListView, in the previous file.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android=""
    android:orientation="vertical" android:layout_width="fill_parent"
    <ListView android:layout_width="wrap_content"
        android:layout_height="wrap_content" android:id="@+id/listView"></ListView>



Don't forget to ask for permission to read the contacts from the system Content Provider.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android=""
    package="org.example.cp" android:versionCode="1" android:versionName="1.0.0">
    <uses-permission android:name="android.permission.READ_CONTACTS" />
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".ContentUserDemo" android:label="@string/app_name">
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />



You should see the list of people from your Contacts printed in your own application.



Published July 6, 2009