How to retrieve Contact name and phone number in A

2019-01-18 13:36发布

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

6条回答
【Aperson】
2楼-- · 2019-01-18 13:45

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 :
                }
            }
        }
    }
查看更多
迷人小祖宗
3楼-- · 2019-01-18 13:57

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();
查看更多
乱世女痞
4楼-- · 2019-01-18 13:58

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.

查看更多
男人必须洒脱
5楼-- · 2019-01-18 13:58
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);

        }

    }
}
}
查看更多
够拽才男人
6楼-- · 2019-01-18 14:06

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");
查看更多
我想做一个坏孩纸
7楼-- · 2019-01-18 14:08

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);
                  }
             }
       }
    }
}
查看更多
登录 后发表回答