9

I'm trying to retrieve contact list with there name and phone numbers. I try following code:

 // Get a cursor over every contact.
    Cursor cursor = getContentResolver().query(People.CONTENT_URI, 
                                               null, null, null, null); 
    // Let the activity manage the cursor lifecycle.
    startManagingCursor(cursor);
    // Use the convenience properties to get the index of the columns
    int nameIdx = cursor.getColumnIndexOrThrow(People.NAME); 

    int phoneIdx = cursor. getColumnIndexOrThrow(People.NUMBER);
    String[] result = new String[cursor.getCount()];
    if (cursor.moveToFirst())
      do { 
        // Extract the name.
        String name = cursor.getString(nameIdx);
        // Extract the phone number.
        String phone = cursor.getString(phoneIdx);
        result[cursor.getPosition()] = name + "-" +" "+  phone;
      } while(cursor.moveToNext());

This code should return an array with the all contacts name and its phone number but this only returns name of the contact and returns NULL in phone number,

Example Output:

 John - null
Cœur
  • 37,241
  • 25
  • 195
  • 267
Arsalan
  • 91
  • 1
  • 1
  • 2
  • I cannot emulate ur problem right now , but like to ask what is the phoneIdx you are getting ? Did u check in database of contact whether those fields are present ? – sat Jan 06 '11 at 08:46

6 Answers6

13

In Android manifest:

    <uses-permission android:name="android.permission.READ_CONTACTS" />

Then in the activity:

editText.setOnFocusChangeListener(new OnFocusChangeListener(){

            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if(hasFocus){
                    editText.setText("");   
                     Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
                     startActivityForResult(intent, PICK_CONTACT);
                }
            }           
        });

And then you have to catch the result of the action pick contact:

@Override 
public void onActivityResult(int reqCode, int resultCode, Intent data){ 
    super.onActivityResult(reqCode, resultCode, data);

    switch(reqCode)
    {
       case (PICK_CONTACT):
         if (resultCode == Activity.RESULT_OK)
         {
             Uri contactData = data.getData();
             Cursor c = managedQuery(contactData, null, null, null, null);
              if (c.moveToFirst())
              {
                  String id = c.getString(c.getColumnIndexOrThrow(ContactsContract.Contacts._ID));

                  String hasPhone = c.getString(c.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));

                  if (hasPhone.equalsIgnoreCase("1")) 
                  {
                      Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null, 
                             ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = "+ id,null, null);
                      phones.moveToFirst();
                      String cNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                       Toast.makeText(getApplicationContext(), cNumber, Toast.LENGTH_SHORT).show();

                      String nameContact = c.getString(c.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME));

                      editText.setText(nameContact+ " "+ cNumber);
                  }
             }
       }
    }
}
chemalarrea
  • 1,385
  • 13
  • 11
3

Don't use deprecated API access like as follow

        Cursor cursor = getContentResolver().
    query( Contacts.CONTENT_URI, 
            new String[]{Contacts.DISPLAY_NAME}, null, null,null);
    if(cursor!=null){
        while(cursor.moveToNext()){
            Cursor c = getContentResolver().query(Phone.CONTENT_URI, new String[]{Phone.NUMBER, Phone.TYPE}, 
                    " DISPLAY_NAME = '"+cursor.getString(cursor.getColumnIndex(Contacts.DISPLAY_NAME))+"'", null, null);
            while(c.moveToNext()){
                switch(c.getInt(c.getColumnIndex(Phone.TYPE))){
                case Phone.TYPE_MOBILE :
                case Phone.TYPE_HOME :
                case Phone.TYPE_WORK :
                case Phone.TYPE_OTHER :
                }
            }
        }
    }
Vivek
  • 4,170
  • 6
  • 36
  • 50
  • How do you then actually read a phone number? When I do `String phone = Phone.NUMBER`, it returned `data1` – learner Apr 22 '13 at 15:49
1

Look on the sample code for retrieve the contacts from android mobile,

    Cursor cursor = context.getContentResolver().query(
                ContactsContract.Contacts.CONTENT_URI, null, null, null, null);


String contactId = cursor.getString(cursor
                    .getColumnIndex(ContactsContract.Contacts._ID));

String name = cursor.getString(cursor                   .getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));

            Cursor phones = context.getContentResolver().query(
                    Phone.CONTENT_URI, null,
                    Phone.CONTACT_ID + " = " + contactId, null, null);
            while (phones.moveToNext()) {
                String number = phones.getString(phones
                        .getColumnIndex(Phone.NUMBER));
                int type = phones.getInt(phones.getColumnIndex(Phone.TYPE));
                switch (type) {
                case Phone.TYPE_HOME:                   
                     Log.i("TYPE_HOME", "" + number);
                    break;
                case Phone.TYPE_MOBILE:                 
                    Log.i("TYPE_MOBILE", "" + number);
                    break;
                case Phone.TYPE_WORK:                   
                     Log.i("TYPE_WORK", "" + number);
                    break;
                case Phone.TYPE_FAX_WORK:                   
                    Log.i("TYPE_FAX_WORK", "" + number);
                    break;
                case Phone.TYPE_FAX_HOME:
                    Log.i("TYPE_FAX_HOME", "" + number);
                    break;

                case Phone.TYPE_OTHER:
                    Log.i("TYPE_OTHER", "" + number);
                    break;
                }
            }
            phones.close();
cursor.close();
bharath
  • 14,283
  • 16
  • 57
  • 95
0
package com.number.contatcs;

import android.app.Activity;

import android.content.Intent;


import android.database.Cursor;

import android.net.Uri;

import android.os.Bundle;

import android.provider.ContactsContract;

import android.provider.ContactsContract.CommonDataKinds.Phone;

import android.view.View;

import android.widget.Button;

import android.widget.EditText;

public class Main2Activity extends Activity {

private static final int CONTACT_PICKER_RESULT = 1001;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main2);
    Button getContacts = (Button) findViewById(R.id.button1);
    getContacts.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            Intent i = new Intent(Intent.ACTION_PICK,
                    ContactsContract.CommonDataKinds.Phone.CONTENT_URI);
            startActivityForResult(i, CONTACT_PICKER_RESULT);

        }
    });
}

protected void onActivityResult(int reqCode, int resultCode, Intent data) {
    super.onActivityResult(reqCode, resultCode, data);
    if (resultCode == RESULT_OK) {
        switch (reqCode) {
        case CONTACT_PICKER_RESULT:
            Cursor cursor = null;
            String number = "";
            String lastName = "";
            try {

                Uri result = data.getData();

                // get the id from the uri
                String id = result.getLastPathSegment();

                // query
                cursor = getContentResolver().query(
                        ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                        null,
                        ContactsContract.CommonDataKinds.Phone._ID
                                + " = ? ", new String[] { id }, null);

                // cursor = getContentResolver().query(Phone.CONTENT_URI,
                // null, Phone.CONTACT_ID + "=?", new String[] { id },
                // null);

                int numberIdx = cursor.getColumnIndex(Phone.DATA);

                if (cursor.moveToFirst()) {
                    number = cursor.getString(numberIdx);
                    // lastName =
                    // cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME));
                } else {
                    // WE FAILED
                }
            } catch (Exception e) {
                // failed
            } finally {
                if (cursor != null) {
                    cursor.close();
                } else {
                }
            }
            EditText numberEditText = (EditText) findViewById(R.id.w);
            numberEditText.setText(number);
            // EditText lastNameEditText =
            // (EditText)findViewById(R.id.last_name);
            // lastNameEditText.setText(lastName);

        }

    }
}
}
kleopatra
  • 51,061
  • 28
  • 99
  • 211
0

HellBoy is right, Phone.xxx is depricated. I did it that way with a lookup-uri:

Uri look = Uri.withAppendedPath(Contacts.CONTENT_LOOKUP_URI, "23N9983726428fnwe");
Intent i = new Intent(Intent.ACTION_VIEW); 
i.setData(look);

Experiment with Contacts.xxx on the first line, you will find the right sollution.

Java_Waldi
  • 924
  • 2
  • 12
  • 29
0

Try the below code.

Cursor managedCursor = getContentResolver()
.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
 new String[] {Phone._ID, Phone.DISPLAY_NAME, Phone.NUMBER}, null, null,  Phone.DISPLAY_NAME + " ASC");
Hussain
  • 5,552
  • 4
  • 40
  • 50
clawash
  • 21
  • 3