Fetch Contacts in android application

前端 未结 5 493
谎友^
谎友^ 2020-12-15 07:17

I was following these links to get the contacts in my application

How to call Android contacts list?

http://www.higherpass.com/Android/Tutorials/Working-Wit

5条回答
  •  悲&欢浪女
    2020-12-15 08:14

    By seeing the answers, I think you got the answer how to fetch contacts and now you want to get the selected contacts on your activity.

    To fetch contact number specific to the contact name:

    ContentResolver contactResolver = getContentResolver(); 
    Cursor cursor = contactResolver.query(Phone.CONTENT_URI, null, Phone.DISPLAY_NAME + "=?", new String[]{contactName}, null);
    
    if(cursor.getCount() > 0){
        cursor.moveToFirst();
        do {
           String number = cursor.getString(mCursor.getColumnIndex(Phone.NUMBER));
        }while (cursor.moveToNext() ); 
    }
    

    Note: Here contactName is the contact name of which you want to fecth contact numbers.

    I am assuming that you have shown the contacts with checkbox in ListView and here is your solution to get the contact list selected by the user to your activity:

    1. Start your contact activity with startActivityForResult().

    2. Initialize ArrayList variable in contact activity say it contactArrayList.

    3. When user checks the checkbox, add this contact in your contactArrayList and keep on adding and when unchecks then remove the contact from the contactArrayList.

    4. When user presses done then set the result ok with the selected contact list which you have added in contactArrayList like this:

    Intent intent = new Intent();
    Bundle bundle = new Bundle();
    bundle.putStringArrayList("contacts", contactArrayList);
    intent.putExtras(bundle);
    setResult(RESULT_OK, intent);
    

    and finish() this activity.

    5. On your calling activity override:

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
            if(resultCode == RESULT_OK && data != null ){
                 Bundle bundle = new Bundle();
                 bundle =  data.getExtras();
                 ArrayList list = bundle.getStringArrayList("contacts");
        }
    }
    

    Note: The above code was tested over 2.3.3.

提交回复
热议问题