选择号码,电子邮件ID和android中的联系人姓名

时间:2013-01-18 06:28:19

标签: android email contacts phone-number

我正在与手机联系人合作。我想从联系人列表中选择一个联系人,当我点击按钮并获取所有联系信息,如姓名,电子邮件和电话号码 .i刚收到电子邮件和联系人姓名,但不能得到电话号码。我的代码在下面给出。

             Intent contactPickerIntent = new Intent(Intent.ACTION_PICK,Contacts.CONTENT_URI);
                            startActivityForResult(contactPickerIntent, PICK_CONTACT);
                     }
             });
     }

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


           if (resultCode == RESULT_OK) {
                switch (reqCode) 
                {
                case PICK_CONTACT:
                    Cursor cursor = null;
                    String email = "", name = "";
                    try {
                        Uri result = data.getData();
                        //Log.v(DEBUG_TAG, "Got a contact result: " + result.toString());

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

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

                        int nameId = cursor.getColumnIndex(Contacts.DISPLAY_NAME);

                        int emailIdx = cursor.getColumnIndex(Email.DATA);


                        if (cursor.moveToFirst()) {
                            email = cursor.getString(emailIdx);
                            name = cursor.getString(nameId);

                        } else {
                           // Log.w(DEBUG_TAG, "No results");
                        }
                    } catch (Exception e) {
                       // Log.e(DEBUG_TAG, "Failed to get email data", e);
                    } finally {
                        if (cursor != null) {
                            cursor.close();
                        }

                        System.out.println(email);
                        System.out.println(name);
                        if (email.length() == 0 && name.length() == 0) 
                        {
                            Toast.makeText(this, "No Email for Selected Contact",Toast.LENGTH_LONG).show();
                        }
                    }
                    break;
                }

            } else {

            }
        }
}

在这里,我可以收到所选用户的电子邮件和姓名。我需要获取所选用户的电子邮件,电话号码和姓名。

6 个答案:

答案 0 :(得分:6)

我之前做过这个,可能会帮助你:

以下是获取联系电话的功能

public void queryAllPhoneNumbersFromContacts(int contactId, List<ListViewEntry> content) {
        final String[] projection = new String[] {
                Phone.NUMBER,
                Phone.TYPE,
        };

        final Cursor phone = managedQuery(
                Phone.CONTENT_URI,  
                projection,
                Data.CONTACT_ID + "=?",
                new String[]{String.valueOf(contactId)},
                null);

        if(phone.moveToFirst()) {
            final int contactNumberColumnIndex = phone.getColumnIndex(Phone.NUMBER);
            final int contactTypeColumnIndex = phone.getColumnIndex(Phone.TYPE);

            while(!phone.isAfterLast()) {
                final String number = phone.getString(contactNumberColumnIndex);
                final int type = phone.getInt(contactTypeColumnIndex);
                content.add(new ListViewEntry(number, Phone.getTypeLabelResource(type),R.string.type_phone));
                phone.moveToNext();
            }

        }
        phone.close();
    }

以下是获取电子邮件ID的功能

    public void queryAllEmailAddressesFromContacts(int contactId, List<ListViewEntry> content) {
    final String[] projection = new String[] {
            Email.DATA,                         // use Email.ADDRESS for API-Level 11+
            Email.TYPE
    };

    final Cursor email = managedQuery(
            Email.CONTENT_URI,  
            projection,
            Data.CONTACT_ID + "=?",
            new String[]{String.valueOf(contactId)},
            null);

    if(email.moveToFirst()) {
        final int contactEmailColumnIndex = email.getColumnIndex(Email.DATA);
        final int contactTypeColumnIndex = email.getColumnIndex(Email.TYPE);

        while(!email.isAfterLast()) {
            final String address = email.getString(contactEmailColumnIndex);
            final int type = email.getInt(contactTypeColumnIndex);
            content.add(new ListViewEntry(address, Email.getTypeLabelResource(type),R.string.type_email));
            email.moveToNext();
        }

    }
    email.close();
}

<强> string.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="type_phone">Phone Number</string>
    <string name="type_email">E-Mail</string>
</resources>

答案 1 :(得分:0)

@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if ( resultCode == RESULT_OK ){
            getContactInfo(data);
            Log.d(TAG, "name " + name + " phone " + phoneNumber );
            if (phoneNumber.length() == 0 || phoneNumber.equals("")) {
                ToastMsg.showToast(HomeActivity.this, "Number Not Avaialable");
            }
            else {
                String id = phoneNumber;
                Log.d(TAG, "phone "+id);
                if (id.contains("*") || id.contains("#")){
                    ToastMsg.showToast(HomeActivity.this, "Not Valid Number");
                }else{

                    ArrayList<ContactSetterGetter> setGet = helper.getAllContacts();

                    Log.d(TAG, "size "+setGet.size());
                    boolean isNumberAvailable = false;
                    if ( setGet.size() != 0 ) {

                        for ( int i = 0; i < setGet.size(); i++){
                            if ( PhoneNumberUtils.compare(id, setGet.get(i).getContactNumber()) ){
                                isNumberAvailable = true;
                            }
                        }

                            if (isNumberAvailable){
                                ToastMsg.showToast(HomeActivity.this, "Contact already Aailable");
                            }else{
                                helper.saveContactInfo(name, phoneNumber, address);
                                ToastMsg.showToast(HomeActivity.this, "Contact Added!");
                                displayContactsInfo();
                            }

                        }else{
                            helper.saveContactInfo(name, phoneNumber, address);
                            ToastMsg.showToast(HomeActivity.this, "Contact Added!");
                            displayContactsInfo();
                        }
                }
            }
            phoneNumber = "";
            name = "No Name";
            address = "";
        }
    }

    private void getContactInfo(Intent intent) {
        ContentResolver cr = getContentResolver();
        Cursor cursor = cr.query(intent.getData(), null, null, null, null);

        while (cursor.moveToNext()) {
            String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
            name = cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME));
            Log.d(TAG, "name " + name);
            String hasPhone = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));

            if (hasPhone.equalsIgnoreCase("1"))
                hasPhone = "true";
            else
                hasPhone = "false";

            if (Boolean.parseBoolean(hasPhone)) {
                Cursor phones = getContentResolver().query( ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,ContactsContract.CommonDataKinds.Phone.CONTACT_ID
                                + " = " + contactId, null, null);
                while (phones.moveToNext()) {
                    phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                    Log.d(TAG, "phone " + phoneNumber);
                }
                phones.close();
            }
        } 
        cursor.close();
    }

答案 2 :(得分:0)

检查this ...

或者你可以这样做..

String hasPhone = cursor.getString(cursor.getColumnIndex(Contacts.HAS_PHONE_NUMBER));

                   if ( hasPhone.equalsIgnoreCase("1"))
                       hasPhone = "true";
                   else
                       hasPhone = "false" ;

                   if (Boolean.parseBoolean(hasPhone)) 
                   {
                    Cursor phones = getContentResolver().query(CommonDataKinds.Phone.CONTENT_URI, null,CommonDataKinds.Phone.CONTACT_ID +" = "+ nameId,null, null);
                    while (phones.moveToNext()) 
                    {
                      String phoneNumber = phones.getString(phones.getColumnIndex(CommonDataKinds.Phone.NUMBER));
                    }
                    phones.close();
                   }

答案 3 :(得分:0)

public class GetContactsDemo extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    readContacts();        
}

public void readContacts(){
     ContentResolver cr = getContentResolver();
     Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
            null, null, null, null);

     if (cur.getCount() > 0) {   
        while (cur.moveToNext()) {
            String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
            String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
            if (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
                System.out.println("name : " + name + ", ID : " + id);

                // get the phone number
                Cursor pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null, 
                                       ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = ?", 
                                       new String[]{id}, null);
                while (pCur.moveToNext()) {
                      String phone = pCur.getString(
                             pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                      System.out.println("phone" + phone);
                } 
                pCur.close();


                // get email and type

               Cursor emailCur = cr.query(        
                        ContactsContract.CommonDataKinds.Email.CONTENT_URI, 
                        null,
                        ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?",  
                        new String[]{id}, null); 
                while (emailCur.moveToNext()) { 
                    // This would allow you get several email addresses
                        // if the email addresses were stored in an array  
                    String email = emailCur.getString(
                                  emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
                    String emailType = emailCur.getString(
                                  emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.TYPE));

                  System.out.println("Email " + email + " Email Type : " + emailType);
                } 
                emailCur.close();

                // Get note.......
                String noteWhere = ContactsContract.Data.CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?"; 
                String[] noteWhereParams = new String[]{id, 
                ContactsContract.CommonDataKinds.Note.CONTENT_ITEM_TYPE}; 
                        Cursor noteCur = cr.query(ContactsContract.Data.CONTENT_URI, null, noteWhere, noteWhereParams, null); 
                if (noteCur.moveToFirst()) { 
                    String note = noteCur.getString(noteCur.getColumnIndex(ContactsContract.CommonDataKinds.Note.NOTE));
                  System.out.println("Note " + note);
                } 
                noteCur.close();

                //Get Postal Address....

                String addrWhere = ContactsContract.Data.CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?"; 
                String[] addrWhereParams = new String[]{id, 
                    ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE}; 
                Cursor addrCur = cr.query(ContactsContract.Data.CONTENT_URI, 
                            null, null, null, null); 
                while(addrCur.moveToNext()) {
                    String poBox = addrCur.getString(
                                 addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.POBOX));
                    String street = addrCur.getString(
                                 addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.STREET));
                    String city = addrCur.getString(
                                 addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.CITY));
                    String state = addrCur.getString(
                                 addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.REGION));
                    String postalCode = addrCur.getString(
                                 addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE));
                    String country = addrCur.getString(
                                 addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.COUNTRY));
                    String type = addrCur.getString(
                                 addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.TYPE));

                    // Do something with these....

                } 
                addrCur.close();

                // Get Instant Messenger.........
                String imWhere = ContactsContract.Data.CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?"; 
                String[] imWhereParams = new String[]{id, 
                    ContactsContract.CommonDataKinds.Im.CONTENT_ITEM_TYPE}; 
                Cursor imCur = cr.query(ContactsContract.Data.CONTENT_URI, 
                        null, imWhere, imWhereParams, null); 
                if (imCur.moveToFirst()) { 
                    String imName = imCur.getString(
                             imCur.getColumnIndex(ContactsContract.CommonDataKinds.Im.DATA));
                    String imType;
                    imType = imCur.getString(
                             imCur.getColumnIndex(ContactsContract.CommonDataKinds.Im.TYPE));
                } 
                imCur.close();

                // Get Organizations.........

                String orgWhere = ContactsContract.Data.CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?"; 
                String[] orgWhereParams = new String[]{id, 
                    ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE}; 
                Cursor orgCur = cr.query(ContactsContract.Data.CONTENT_URI, 
                            null, orgWhere, orgWhereParams, null);
                if (orgCur.moveToFirst()) { 
                    String orgName = orgCur.getString(orgCur.getColumnIndex(ContactsContract.CommonDataKinds.Organization.DATA));
                    String title = orgCur.getString(orgCur.getColumnIndex(ContactsContract.CommonDataKinds.Organization.TITLE));
                } 
                orgCur.close();
            }
            System.out.println("name :"+ name);
            System.out.println("name :"+ id);
        }

   }
}

}

答案 4 :(得分:0)

public void getContact() {
   // startActivityForResult(new Intent(getActivity(), ContactsPickerActivity.class), GET_PHONE_NUMBER);
    Intent contactPickerIntent =
            new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
    startActivityForResult(contactPickerIntent, GET_PHONE_NUMBER);
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data){

    super.onActivityResult(requestCode, resultCode, data);
    // See which child activity is calling us back.

    String name =null;
    String phone=null;
    String email=null;
    Toast.makeText(getActivity(),"dfg",Toast.LENGTH_SHORT).show();
    switch (requestCode) {
        case GET_PHONE_NUMBER:
            String DEBUG_TAG ="tag";
            Cursor cursor = null;
            Cursor phonecursor = null;
            Uri result = data.getData();
            String id = result.getLastPathSegment();

            cursor = getActivity().getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=?", new String[] { id }, null);
            int phoneIdx = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DATA);
            int nameIdx =cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
            if (cursor.moveToFirst()) {
                while (cursor.isAfterLast() == false) {
                    phone = cursor.getString(phoneIdx);
                    name = cursor.getString(nameIdx);
                    cursor.moveToNext();
                }
            } else {
                //no results actions
            }
            email = "";
            try {

                Log.v(DEBUG_TAG, "Got a contact result: "
                        + result.toString());

                // get the contact id from the Uri


                // query for everything email
                cursor = getActivity().getContentResolver().query(ContactsContract.CommonDataKinds.Email.CONTENT_URI,
                        null, ContactsContract.CommonDataKinds.Email.CONTACT_ID + "=?", new String[] { id },
                        null);

                int emailIdx = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA);

                // let's just get the first email
                if (cursor.moveToFirst()) {
                    email = cursor.getString(emailIdx);
                    Log.v(DEBUG_TAG, "Got email: " + email + " " + name + " " + phone);
                    Toast.makeText(getActivity(),email
                            +phone,Toast.LENGTH_SHORT).show();


                } else {
                    Log.w(DEBUG_TAG, "No results");
                }
            } catch (Exception e) {
                Log.e(DEBUG_TAG, "Failed to get email data", e);
            } finally {
                if (cursor != null) {
                    cursor.close();
                }}
            SingleContact sc = new SingleContact();
            sc.SetData(name,phone,email);
            sm.saveNumber(phone);
            contactlist.add(sc);
            cla.notifyDataSetChanged();
            break;

        default:
            break;
    }
}

答案 5 :(得分:-1)

像这样修改你的onActivityResult()方法

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

    if (resultCode == RESULT_OK&& reqCode == PICK_CONTACT) {

        Cursor cursor = null,phoneCursor=null;
        String email = "", name = "",number ="";
        try {
            Uri result = data.getData();
            //Log.v(DEBUG_TAG, "Got a contact result: " + result.toString());

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

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



            int emailIdx;
            if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.HONEYCOMB)
                emailIdx = cursor.getColumnIndex(Email.ADDRESS);
            else
                emailIdx = cursor.getColumnIndex(Email.DATA);


            if (cursor.moveToFirst()) {
                email = cursor.getString(emailIdx);

            }
    // query for  phone number
            phoneCursor = getContentResolver().query(Phone.CONTENT_URI, null, 
                    Phone.CONTACT_ID + "=?", new String[]{id}, null);
            int numberIdx = phoneCursor.getColumnIndex(Phone.NUMBER);
            int nameId = phoneCursor.getColumnIndex(Contacts.DISPLAY_NAME);

            if(phoneCursor.moveToFirst()){
                number = phoneCursor.getString(numberIdx);
                name = phoneCursor.getString(nameId);                   
            }

        } catch (Exception e) {
            // Log.e(DEBUG_TAG, "Failed to get email data", e);
        } finally {
            if (cursor != null) {
                cursor.close();
            }    
            if (phoneCursor != null) {
                phoneCursor.close();
            }    
        }                


    } 
}