Tuesday, August 7, 2012

Query data from the Contacts content provider for Android

Android ships with a number of content providers for common data types (audio, video, images, personal contact information, and so on). You can see some of them listed in the android.provider package. You can query these providers for the data they contain (although, for some, you must acquire the proper permission to read the data).



package com.GetContact;

import android.app.Activity;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Contacts.People;
import android.widget.TextView;

public class GetContactActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        TextView tvContacts = (TextView)findViewById(R.id.contacts);
        
        String[] contacts = new String[] {People.NAME, People.NUMBER};
        Uri contentUri = People.CONTENT_URI;
        Cursor cursor = managedQuery(contentUri, contacts, null, null, null);
        
        String textContacts = "";
        
        if (cursor.moveToFirst()) {
         String myname = null;
         String mynumber = null;
         do {
          textContacts = textContacts
           + cursor.getString(cursor.getColumnIndex(People.NAME)) + " : "
           + cursor.getString(cursor.getColumnIndex(People.NUMBER)) + "\n";
         } while (cursor.moveToNext()); 
         
         tvContacts.setText(textContacts);
        }
    }
}


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView  
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="@string/hello"
    />
<TextView  
    android:id="@+id/contacts"
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    />
</LinearLayout>



In order to query data from the Contacts content provider, we have to grant permission of "android.permission.READ_CONTACTS".

No comments:

Post a Comment