Pick a Number and Name From Contacts List in andro

2019-01-07 15:03发布

i want to pick a contact with it's number from my contacts list. i read a lot of solutions and research for couple weeks but all of articles didn't work properly. some codes like following:

Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(intent, PICK_CONTACT);

// and in activityresult:

if (resultCode == Activity.RESULT_OK) {
            Uri contactData = data.getData();
            Cursor c =  managedQuery(contactData, null, null, null, null);
            if (c.moveToFirst()) {
              String name = c.getString(c.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME));
              tv1.setText(name);
            }
          }

or this code for getting all contacts but i cant have the number of 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()); 
tv1.setText(textContacts);
}

can anyone help me plz? my android is 2.3.3

12条回答
萌系小妹纸
2楼-- · 2019-01-07 15:38

try following code,

Intent intent = new Intent(Intent.ACTION_PICK);                          
intent.setType(ContactsContract.Contacts._ID);                          
startActivityForResult(intent, PICK_CONTACT);                          

 public void onActivityResult(int requestCode, int resultCode, Intent intent)  
 {          
    if (requestCode == PICK_CONTACT)         
    { 
          Cursor cursor =  managedQuery(Email.CONTENT_URI, null, Email.CONTACT_ID +  " = " + intent.getData(), null, null);                 
          cursor.moveToNext();                 
          String contactId = cursor.getString(cursor.getColumnIndex(Email._ID));
          String  name = cursor.getString(cursor.getColumnIndexOrThrow(Email.DATA1));                   
          Toast.makeText(this, "Contect LIST  =  "+name, Toast.LENGTH_LONG).show();            
   }
}
查看更多
走好不送
3楼-- · 2019-01-07 15:40

This may help you:

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

        try {
            if (resultCode == Activity.RESULT_OK) {
                Uri contactData = data.getData();
                Cursor cur = managedQuery(contactData, null, null, null, null);
                ContentResolver contect_resolver = getContentResolver();

                if (cur.moveToFirst()) {
                    String id = cur.getString(cur.getColumnIndexOrThrow(ContactsContract.Contacts._ID));
                    String name = "";
                    String no = "";

                    Cursor phoneCur = contect_resolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
                            ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[]{id}, null);

                    if (phoneCur.moveToFirst()) {
                        name = phoneCur.getString(phoneCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
                        no = phoneCur.getString(phoneCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                    }

                    Log.e("Phone no & name :***: ", name + " : " + no);
                    txt.append(name + " : " + no + "\n");

                    id = null;
                    name = null;
                    no = null;
                    phoneCur = null;
                }
                contect_resolver = null;
                cur = null;
                //                      populateContacts();
            }
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
            Log.e("IllegalArgumentException::", e.toString());
        } catch (Exception e) {
            e.printStackTrace();
            Log.e("Error :: ", e.toString());
        }
    }
查看更多
啃猪蹄的小仙女
4楼-- · 2019-01-07 15:42

Add a permission to read contacts data to your application manifest.

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

Use Intent.Action_Pick in your Activity like below

Intent contactPickerIntent = new Intent(Intent.ACTION_PICK,
                ContactsContract.CommonDataKinds.Phone.CONTENT_URI);
        startActivityForResult(contactPickerIntent, RESULT_PICK_CONTACT);

Then Override the onActivityResult()

 @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // check whether the result is ok
        if (resultCode == RESULT_OK) {
            // Check for the request code, we might be usign multiple startActivityForReslut
            switch (requestCode) {
            case RESULT_PICK_CONTACT:
               Cursor cursor = null;
        try {
            String phoneNo = null ;
            String name = null;           
            Uri uri = data.getData();            
            cursor = getContentResolver().query(uri, null, null, null, null);
            cursor.moveToFirst();           
            int  phoneIndex =cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
            phoneNo = cursor.getString(phoneIndex); 

            textView2.setText(phoneNo);
        } catch (Exception e) {
            e.printStackTrace();
        }
                break;
            }
        } else {
            Log.e("MainActivity", "Failed to pick contact");
        }
    }

This will work check it out

查看更多
Rolldiameter
5楼-- · 2019-01-07 15:47

If you want to pick a contact from contact list on click or focus event then copy this code and paste in Your activity.

  • FOCUS EVENT OF EDIT TEXT:

     phoneNo.setOnFocusChangeListener(new OnFocusChangeListener()
      {   public void onFocusChange(View v, boolean hasFocus) 
          {
             Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
             startActivityForResult(intent,PICK_CONTACT );//PICK_CONTACT is private static final int, so declare in activity class
       } });
    
  • A FUNCTION TO GET THE CONTACT NAME AND PHONE NO IS :

      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 phn_no = phones.getString(phones.getColumnIndex("data1"));
                    String name = c.getString(c.getColumnIndex(StructuredPostal.DISPLAY_NAME));
                   Toast.makeText(this, "contact info : "+ phn_no+"\n"+name, Toast.LENGTH_LONG).show();
    
                  }
                    }
                 }
            }
    

    }

查看更多
别忘想泡老子
6楼-- · 2019-01-07 15:47

This code will work for mobile number contacts, not for email or something. i found this code simplest. let me know if there is any problem.

start activity with pick intent on phone data type:

findViewById(R.id.choose_contact_button).setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
            Intent pickContact = new Intent(Intent.ACTION_PICK, ContactsContract.CommonDataKinds.Phone.CONTENT_URI);
            startActivityForResult(pickContact, PICK_CONTACT_REQUEST);
      }
 });

Now set onAcitivityResult();

@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent){
        switch (requestCode){
            case PICK_CONTACT_REQUEST:
                if (resultCode == RESULT_OK){
                    Uri contactUri = intent.getData();
                    Cursor nameCursor = getContentResolver().query(contactUri, null, null, null, null);
                    if (nameCursor.moveToFirst()){
                        String name = nameCursor.getString(nameCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
                        String number = nameCursor.getString(nameCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                        ((EditText)findViewById(R.id.person_name)).setText(name);
                        ((EditText)findViewById(R.id.enter_mobile)).setText(number);
                        nameCursor.close();
                    }
                }
                break;
        }
    }
查看更多
爷、活的狠高调
7楼-- · 2019-01-07 15:49

Without manifest or run time permissions you can try this.

To pickup the name and contact number both from contacts app. By this code the contact app will also show the number below the contact name.

The code is to pick only single name and number from contacts app.

private void openContactSelectionIntent() {
        Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
        intent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE);
        startActivityForResult(Intent.createChooser(intent, "Select Contact"), RC_SELECT_CONTACT);
    }

And here is onActivityResult method's code

Uri uri1 = data.getData();
                Cursor c = managedQuery(uri1, null, null, null, null);
                if (c.moveToFirst()) {
                    String name = c.getString(c.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
                    System.out.println("name is: " + name);

                }



                Cursor cursor = getContentResolver().query(uri1, null, null, null, null);
                if (null == cursor) return;
                try {
                    while (cursor.moveToNext()) {
                        String number = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
                        System.out.println("number is "+number);
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }finally {
                    cursor.close();
                }
查看更多
登录 后发表回答