Get Contact Emails By Content Provider - Android Example

DOWNLOAD CODE

Related Examples

In this example reading contact emails from phone. showing visual reprsentation of contact data to how data stored and how we can fetch data by contant provider.

 

If you are begginner then firstly read this example:
Content Providers Basics

 

Content provider show data to content resolver as one or many tables that will show same as relational database.

 

Contact Data Storage :

Get Contact Emails By Content Provider

 

As you have seen in image ContactsContract.Data table contains all the contact data in its rows. Android use ContactsContract.Data Table as a generic class so contact data is stored in columns DATA1 ... TO ...DATA15 depends on MIMETYPE column.

MIMETYPE column defines what type of data stored in the rows of ContactsContract.Data Table.

  Example :

    If MIMETYPE column has value Email.CONTENT_ITEM_TYPE then DATA1 column will contain a email address.
    If MIMETYPE column has value Phone.CONTENT_ITEM_TYPE then DATA1 column will contain a phone number.

 

ContactsContract.Data table is a generic table and defines column names as DATA1 to DATA15, its hard to developer to get which column contains what value beacause of that Android provides CommonDataKinds Class.

If you want to fetch contact email then use CommonDataKinds.Email class.

If you want to fetch contact phone then use CommonDataKinds.Phone class.

CommonDataKinds class constants directly pointed to ContactsContract.Data table Columns.

You can also use ContactsContract.Data table Columns names(DATA1 .. DATA15) to in query to fetch contact data.

 

AndroidManifest.xml

   <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.androidexample.contentprovideremail"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.androidexample.contentprovideremail.MainActivity"
            android:label="@string/app_name" >
            <intent-filter> 
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
    
   <uses-permission android:name="android.permission.READ_CONTACTS" />

</manifest>

 

MainActivity.java


package com.androidexample.contentprovideremail;

import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.ContactsContract.Data;
import android.app.Activity;
import android.content.ContentResolver;
import android.database.Cursor;
import android.util.Log;
import android.widget.TextView;

public class MainActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		TextView output = (TextView) findViewById(R.id.output);
		
		// Fetch emails from contact list
		String emailStr = refreshData();
		// Show emails on screen
		output.setText(emailStr);
		
	}

	
	private String refreshData() {
       String emaildata = "";
        
       try {

            /**************************************************/
            
            ContentResolver cr = getBaseContext()
                    .getContentResolver();
            Cursor cur = cr
                    .query(ContactsContract.Contacts.CONTENT_URI,
                            null,
                            null,
                            null,
                            null);
            
            if (cur.getCount() > 0) {
                
                Log.i("Content provider", "Reading contact  emails");
                
                while (cur
                        .moveToNext()) {
                    
                    String contactId = cur
                            .getString(cur
                                    .getColumnIndex(ContactsContract.Contacts._ID));
                
                            // Create query to use CommonDataKinds classes to fetch emails
                            Cursor emails = cr.query(
                                    ContactsContract.CommonDataKinds.Email.CONTENT_URI,
                                    null,
                                    ContactsContract.CommonDataKinds.Email.CONTACT_ID
                                            + " = " + contactId, null, null);
                            
                            /*
                            //You can use all columns defined for ContactsContract.Data 
                            // Query to get phone numbers by directly call data table column
                              
                            Cursor c = getContentResolver().query(Data.CONTENT_URI,
                                      new String[] {Data._ID, Phone.NUMBER, Phone.TYPE, Phone.LABEL},
                                      Data.CONTACT_ID + "=?" + " AND "
                                              + Data.MIMETYPE + "= + Phone.CONTENT_ITEM_TYPE + ",
                                      new String[] {String.valueOf(contactId)}, null);
                            */
                            
                            while (emails.moveToNext()) {
                                
                                // This would allow you get several email addresses
                                String emailAddress = emails
                                    .getString(emails
                                        .getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
                               
                                //Log.e("email==>", emailAddress);
                               
                                emaildata +="
  "+emailAddress+"
"
                                            +"--------------------------------------";
                             }
                            
                            emails.close();
                        }
                
            }
            else
            {
                emaildata +="
Data not found.
";
                
            }
            cur.close();
            

        } catch (Exception e) {
            
             emaildata +="
Exception : "+e+"
";
        }
        
        return emaildata;
	}

}
        

 

AndroidManifest.xml

  <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

    <TextView
        android:id="@+id/output"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Getting Emails ...." />

</RelativeLayout>

 

 

How To Test In Simulator :

 

Add email to simulator click menu button
 
click_new_contact_3 Fill contact details and save
 
Now Run Example : Run your example