fsdf fsd
fsdf fsd

Reputation: 1321

android get all contacts

How can I get all the names of the contacts in my Android and put them into array of strings?

Upvotes: 122

Views: 182937

Answers (10)

Shah Nizar Baloch
Shah Nizar Baloch

Reputation: 63

I am using this method, and it is working perfectly. It gets fav, picture, name, number etc. (All the details of the contact). And also it is not repetitive.

List

private static List<FavContact> contactList = new ArrayList<>();

Method to get contacts

@SuppressLint("Range")
public static void readContacts(Context context) {

    if (context == null)
        return;

    ContentResolver contentResolver = context.getContentResolver();

    if (contentResolver == null)
        return;

    String[] fieldListProjection = {
            ContactsContract.CommonDataKinds.Phone.CONTACT_ID,
            ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME_PRIMARY,
            ContactsContract.CommonDataKinds.Phone.NUMBER,
            ContactsContract.CommonDataKinds.Phone.NORMALIZED_NUMBER,
            ContactsContract.Contacts.HAS_PHONE_NUMBER,
            ContactsContract.Contacts.PHOTO_URI
            ,ContactsContract.Contacts.STARRED
    };
    String sort = ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME_PRIMARY + " ASC";
    Cursor phones = contentResolver
            .query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI
                    , fieldListProjection, null, null, sort);
    HashSet<String> normalizedNumbersAlreadyFound = new HashSet<>();

    if (phones != null && phones.getCount() > 0) {
        while (phones.moveToNext()) {
            String normalizedNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));

            if (Integer.parseInt(phones.getString(phones.getColumnIndex(
                    ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
                if (normalizedNumbersAlreadyFound.add(normalizedNumber)) {

                    int id = phones.getInt(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID));
                    String name = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
                    String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                    int fav = phones.getInt(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.STARRED));
                    boolean isFav;
                    isFav= fav == 1;

                    String uri = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.PHOTO_URI));
                    if(uri!=null){
                        contactList.add(new FavContact(id,isFav,uri,name,phoneNumber));
                    }
                    else{
                        contactList.add(new FavContact(id,isFav,name,phoneNumber));
                    }

                }
            }
        }
        phones.close();
    }
}

Model Class

public class FavContact{

    private int id;

    private boolean isFavorite;

    private String image;

    private String name;

    private String number;
   

    public FavContact(int id,boolean isFavorite, String image, String name, String number){
        this.id=id;
        this.isFavorite = isFavorite;
        this.image = image;
        this.name = name;
        this.number = number;
    }

    public FavContact(int id,boolean isFavorite, String name, String number){
        this.id=id;
        this.isFavorite = isFavorite;
        this.name = name;
        this.number = number;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public boolean isFavorite() {
        return isFavorite;
    }

    public void setFavorite(boolean favorite) {
        isFavorite = favorite;
    }

    public String getImage() {
        return image;
    }

    public void setImage(String image) {
        this.image = image;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getNumber() {
        return number;
    }

    public void setNumber(String number) {
        this.number = number;
    }

}

Adapter

public class ContactAdapter extends RecyclerView.Adapter<ContactAdapter.MyViewHolder> implements Filterable {

private final Context context;
private final List<FavContact> contactList;
private final List<FavContact> filterList;
private final OnMyOwnClickListener onMyOwnClickListener;
private final FavContactRepo favContactRepo;

public ContactAdapter(Application application,Context context, List<FavContact> contactList, OnMyOwnClickListener onMyOwnClickListener) {
    this.context = context;
    this.contactList = contactList;
    this.onMyOwnClickListener = onMyOwnClickListener;
    filterList = new ArrayList<>(contactList);
    favContactRepo = new FavContactRepo(application);
}

@NonNull
@Override
public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    final LayoutInflater inflater = LayoutInflater.from(context);
    @SuppressLint("InflateParams") final View view = inflater.inflate(R.layout.design_fav_contact, null, false);
    return new MyViewHolder(view,onMyOwnClickListener);
}

@Override
public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
    final FavContact obj = contactList.get(position);
    holder.tv_contact_name.setText(obj.getName());

    holder.tv_contact_number.setText(obj.getNumber());

    if(obj.getImage()==null){
        Picasso.get().load(R.drawable.ic_circle_fav_no_dp).fit().into(holder.img_contact);
    }
    else{
        Bitmap bp;
        try {
            bp = MediaStore.Images.Media
                    .getBitmap(context.getContentResolver(),
                            Uri.parse(obj.getImage()));
            Glide.with(context).load(bp).centerInside().into(holder.img_contact);
        } catch (IOException e) {
            e.printStackTrace();
            Picasso.get().load(R.drawable.ic_circle_fav_no_dp).fit().into(holder.img_contact);
        }

    }
    obj.setFavorite(favContactRepo.checkIfFavourite(obj.getId()));

    if(obj.isFavorite()){
        Picasso.get().load(R.drawable.ic_menu_favorite_true).into(holder.img_fav_true_or_not);
    }
    else{
        Picasso.get().load(R.drawable.ic_menu_favorite_false).into(holder.img_fav_true_or_not);
    }

}

@Override
public int getItemCount() {
    return contactList.size();
}

@Override
public long getItemId(int position) {
    return position;
}
@Override
public int getItemViewType(int position) {
    return position;
}

static class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
    CircleImageView img_contact;
    TextView tv_contact_name,tv_contact_number;
    ImageView img_fav_true_or_not;
    ImageView img_call;
    RecyclerView fav_contact_rv;

    OnMyOwnClickListener onMyOwnClickListener;
    public MyViewHolder(@NonNull View itemView, OnMyOwnClickListener onMyOwnClickListener) {
        super(itemView);
        img_contact = itemView.findViewById(R.id.img_contact);
        tv_contact_name = itemView.findViewById(R.id.tv_contact_name);
        img_fav_true_or_not = itemView.findViewById(R.id.img_fav_true_or_not);
        tv_contact_number = itemView.findViewById(R.id.tv_contact_number);
        img_call = itemView.findViewById(R.id.img_call);
        fav_contact_rv = itemView.findViewById(R.id.fav_contact_rv);

        this.onMyOwnClickListener = onMyOwnClickListener;
        img_call.setOnClickListener(this);
        img_fav_true_or_not.setOnClickListener(this);
        img_contact.setOnClickListener(this);
        itemView.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        onMyOwnClickListener.onMyOwnClick(getAbsoluteAdapterPosition(),view);
    }
}

public interface OnMyOwnClickListener{
    void onMyOwnClick(int position,View view);
}


@Override
public Filter getFilter() {
    return filteredList;
}

public Filter filteredList = new Filter() {
    @Override
    protected FilterResults performFiltering(CharSequence constraint) {
        List<FavContact> filteredList = new ArrayList<>();
        if (constraint == null || constraint.length() == 0) {
            filteredList=filterList;
        } else {
            String filterText = constraint.toString().toLowerCase().trim();
            for (FavContact item : filterList) {
                if (item.getName().toLowerCase().contains(filterText)
                        ||item.getNumber().toLowerCase().contains(filterText)) {
                    filteredList.add(item);
                }
            }

        }

        FilterResults results = new FilterResults();
        results.values = filteredList;

        return results;
    }

    @SuppressLint("NotifyDataSetChanged")
    @Override
    protected void publishResults(CharSequence constraint, FilterResults results) {
        contactList.clear();
        contactList.addAll((ArrayList)results.values);
        notifyDataSetChanged();

    }
};

Demo

Upvotes: 1

ShehryarAhmed
ShehryarAhmed

Reputation: 91

//In Kotlin     
private fun showContacts() {
        // Check the SDK version and whether the permission is already granted or not.
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && checkSelfPermission(
                requireContext(),
                Manifest.permission.READ_CONTACTS
            ) != PackageManager.PERMISSION_GRANTED
        ) {
            requestPermissions(
                arrayOf(Manifest.permission.READ_CONTACTS),
                1001
            )
            //After this point you wait for callback in onRequestPermissionsResult(int, String[], int[]) overriden method
        } else {
            // Android version is lesser than 6.0 or the permission is already granted.
            getContactList()
        }
    }
    private fun getContactList() {
        val cr: ContentResolver = requireActivity().contentResolver
        val cur: Cursor? = cr.query(
            ContactsContract.Contacts.CONTENT_URI,
            null, null, null, null
        )
        if ((if (cur != null) cur.getCount() else 0) > 0) {
            while (cur != null && cur.moveToNext()) {
                val id: String = cur.getString(
                    cur.getColumnIndex(ContactsContract.Contacts._ID)
                )
                val name: String = cur.getString(
                    cur.getColumnIndex(
                        ContactsContract.Contacts.DISPLAY_NAME
                    )
                )
                if (cur.getInt(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER)) > 0) {
                    val pCur: Cursor? = cr.query(
                        ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                        null,
                        ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
                        arrayOf(id),
                        null
                    )
                    pCur?.let {
                        while (pCur.moveToNext()) {
                            val phoneNo: String = pCur.getString(
                                pCur.getColumnIndex(
                                    ContactsContract.CommonDataKinds.Phone.NUMBER
                                )
                            )
                            Timber.i("Name: $name")
                            Timber.i("Phone Number: $phoneNo")
                        }
                        pCur.close()
                    }

                }
            }
        }
        if (cur != null) {
            cur.close()
        }
    }

Upvotes: 2

jay patoliya
jay patoliya

Reputation: 761

Get all contacts in less than a second and without any load in your activity. Follow my steps works like a charm.

ArrayList<Contact> contactList = new ArrayList<>();

private static final String[] PROJECTION = new String[]{
        ContactsContract.CommonDataKinds.Phone.CONTACT_ID,
        ContactsContract.Contacts.DISPLAY_NAME,
        ContactsContract.CommonDataKinds.Phone.NUMBER
};

private void getContactList() {
    ContentResolver cr = getContentResolver();

    Cursor cursor = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, PROJECTION, null, null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC");
    if (cursor != null) {
        HashSet<String> mobileNoSet = new HashSet<String>();
        try {
            final int nameIndex = cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
            final int numberIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);

            String name, number;
            while (cursor.moveToNext()) {
                name = cursor.getString(nameIndex);
                number = cursor.getString(numberIndex);
                number = number.replace(" ", "");
                if (!mobileNoSet.contains(number)) {
                    contactList.add(new Contact(name, number));
                    mobileNoSet.add(number);
                    Log.d("hvy", "onCreaterrView  Phone Number: name = " + name
                            + " No = " + number);
                }
            }
        } finally {
            cursor.close();
        }
    }
}

Contacts


public class Contact {
public String name;
public String phoneNumber;

public Contact() {
}

public Contact(String name, String phoneNumber ) {
    this.name = name;
    this.phoneNumber = phoneNumber;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getPhoneNumber() {
    return phoneNumber;
}

public void setPhoneNumber(String phoneNumber) {
    this.phoneNumber = phoneNumber;
}

}

Benefits

  • less than a second
  • without load
  • ascending order
  • without duplicate contacts

Upvotes: 21

DragonFire
DragonFire

Reputation: 4082

Improving on the answer of @Adiii - It Will Cleanup The Phone Number and Remove All Duplicates

Declare a Global Variable

// Hash Maps
Map<String, String> namePhoneMap = new HashMap<String, String>();

Then Use The Function Below

private void getPhoneNumbers() {

        Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);

        // Loop Through All The Numbers
        while (phones.moveToNext()) {

            String name = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
            String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));

            // Cleanup the phone number
            phoneNumber = phoneNumber.replaceAll("[()\\s-]+", "");

            // Enter Into Hash Map
            namePhoneMap.put(phoneNumber, name);

        }

        // Get The Contents of Hash Map in Log
        for (Map.Entry<String, String> entry : namePhoneMap.entrySet()) {
            String key = entry.getKey();
            Log.d(TAG, "Phone :" + key);
            String value = entry.getValue();
            Log.d(TAG, "Name :" + value);
        }

        phones.close();

    }

Remember in the above example the key is phone number and value is a name so read your contents like 998xxxxx282->Mahatma Gandhi instead of Mahatma Gandhi->998xxxxx282

Upvotes: 6

Coldfin Lab
Coldfin Lab

Reputation: 361

//GET CONTACTLIST WITH ALL FIELD...       

public ArrayList < ContactItem > getReadContacts() {
         ArrayList < ContactItem > contactList = new ArrayList < > ();
         ContentResolver cr = getContentResolver();
         Cursor mainCursor = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
         if (mainCursor != null) {
          while (mainCursor.moveToNext()) {
           ContactItem contactItem = new ContactItem();
           String id = mainCursor.getString(mainCursor.getColumnIndex(ContactsContract.Contacts._ID));
           String displayName = mainCursor.getString(mainCursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));

           Uri contactUri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, Long.parseLong(id));
           Uri displayPhotoUri = Uri.withAppendedPath(contactUri, ContactsContract.Contacts.Photo.DISPLAY_PHOTO);

           //ADD NAME AND CONTACT PHOTO DATA...
           contactItem.setDisplayName(displayName);
           contactItem.setPhotoUrl(displayPhotoUri.toString());

           if (Integer.parseInt(mainCursor.getString(mainCursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
            //ADD PHONE DATA...
            ArrayList < PhoneContact > arrayListPhone = new ArrayList < > ();
            Cursor phoneCursor = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[] {
             id
            }, null);
            if (phoneCursor != null) {
             while (phoneCursor.moveToNext()) {
              PhoneContact phoneContact = new PhoneContact();
              String phone = phoneCursor.getString(phoneCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
              phoneContact.setPhone(phone);
              arrayListPhone.add(phoneContact);
             }
            }
            if (phoneCursor != null) {
             phoneCursor.close();
            }
            contactItem.setArrayListPhone(arrayListPhone);


            //ADD E-MAIL DATA...
            ArrayList < EmailContact > arrayListEmail = new ArrayList < > ();
            Cursor emailCursor = cr.query(ContactsContract.CommonDataKinds.Email.CONTENT_URI, null, ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?", new String[] {
             id
            }, null);
            if (emailCursor != null) {
             while (emailCursor.moveToNext()) {
              EmailContact emailContact = new EmailContact();
              String email = emailCursor.getString(emailCursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
              emailContact.setEmail(email);
              arrayListEmail.add(emailContact);
             }
            }
            if (emailCursor != null) {
             emailCursor.close();
            }
            contactItem.setArrayListEmail(arrayListEmail);

            //ADD ADDRESS DATA...
            ArrayList < PostalAddress > arrayListAddress = new ArrayList < > ();
            Cursor addrCursor = getContentResolver().query(ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_URI, null, ContactsContract.CommonDataKinds.StructuredPostal.CONTACT_ID + " = ?", new String[] {
             id
            }, null);
            if (addrCursor != null) {
             while (addrCursor.moveToNext()) {
              PostalAddress postalAddress = new PostalAddress();
              String city = addrCursor.getString(addrCursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.CITY));
              String state = addrCursor.getString(addrCursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.REGION));
              String country = addrCursor.getString(addrCursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.COUNTRY));
              postalAddress.setCity(city);
              postalAddress.setState(state);
              postalAddress.setCountry(country);
              arrayListAddress.add(postalAddress);
             }
            }
            if (addrCursor != null) {
             addrCursor.close();
            }
            contactItem.setArrayListAddress(arrayListAddress);
           }
           contactList.add(contactItem);
          }
         }
         if (mainCursor != null) {
          mainCursor.close();
         }
         return contactList;
        }



    //MODEL...
        public class ContactItem {

            private String displayName;
            private String photoUrl;
            private ArrayList<PhoneContact> arrayListPhone = new ArrayList<>();
            private ArrayList<EmailContact> arrayListEmail = new ArrayList<>();
            private ArrayList<PostalAddress> arrayListAddress = new ArrayList<>();


            public String getDisplayName() {
                return displayName;
            }

            public void setDisplayName(String displayName) {
                this.displayName = displayName;
            }

            public String getPhotoUrl() {
                return photoUrl;
            }

            public void setPhotoUrl(String photoUrl) {
                this.photoUrl = photoUrl;
            }

            public ArrayList<PhoneContact> getArrayListPhone() {
                return arrayListPhone;
            }

            public void setArrayListPhone(ArrayList<PhoneContact> arrayListPhone) {
                this.arrayListPhone = arrayListPhone;
            }

            public ArrayList<EmailContact> getArrayListEmail() {
                return arrayListEmail;
            }

            public void setArrayListEmail(ArrayList<EmailContact> arrayListEmail) {
                this.arrayListEmail = arrayListEmail;
            }

            public ArrayList<PostalAddress> getArrayListAddress() {
                return arrayListAddress;
            }

            public void setArrayListAddress(ArrayList<PostalAddress> arrayListAddress) {
                this.arrayListAddress = arrayListAddress;
            }
        }

        public class EmailContact
        {
            private String email = "";

            public String getEmail() {
                return email;
            }

            public void setEmail(String email) {
                this.email = email;
            }
        }

        public class PhoneContact
        {
            private String phone="";

            public String getPhone()
            {
                return phone;
            }

            public void setPhone(String phone) {
                this.phone = phone;
            }
        }


        public class PostalAddress
        {
            private String city="";
            private String state="";
            private String country="";

            public String getCity() {
                return city;
            }

            public void setCity(String city) {
                this.city = city;
            }

            public String getState() {
                return state;
            }

            public void setState(String state) {
                this.state = state;
            }

            public String getCountry() {
                return country;
            }

            public void setCountry(String country) {
                this.country = country;
            }
        }

Upvotes: 2

M Talha
M Talha

Reputation: 189

This is the Method to get contact list Name and Number

 private void getAllContacts() {
    ContentResolver contentResolver = getContentResolver();
    Cursor cursor = contentResolver.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC");
    if (cursor.getCount() > 0) {
        while (cursor.moveToNext()) {

            int hasPhoneNumber = Integer.parseInt(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER)));
            if (hasPhoneNumber > 0) {
                String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
                String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
                Cursor phoneCursor = contentResolver.query(
                        ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                        null,
                        ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[]{id},
                        null);
                if (phoneCursor != null) {
                    if (phoneCursor.moveToNext()) {
                        String phoneNumber = phoneCursor.getString(phoneCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));

   //At here You can add phoneNUmber and Name to you listView ,ModelClass,Recyclerview
                        phoneCursor.close();
                    }


                }
            }
        }
    }
}

Upvotes: 2

Jigar Pandya
Jigar Pandya

Reputation: 5977

Cursor contacts = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
String aNameFromContacts[] = new String[contacts.getCount()];  
String aNumberFromContacts[] = new String[contacts.getCount()];  
int i = 0;

int nameFieldColumnIndex = contacts.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
int numberFieldColumnIndex = contacts.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);

while(contacts.moveToNext()) {

    String contactName = contacts.getString(nameFieldColumnIndex);
    aNameFromContacts[i] =    contactName ; 

    String number = contacts.getString(numberFieldColumnIndex);
    aNumberFromContacts[i] =    number ;
i++;
}

contacts.close();

The result will be aNameFromContacts array full of contacts. Also ensure that you have added

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

in main.xml

Upvotes: 3

Masoud Siahkali
Masoud Siahkali

Reputation: 5311

Get contacts info , photo contacts , photo uri and convert to Class model

1). Sample for Class model :

    public class ContactModel {
        public String id;
        public String name;
        public String mobileNumber;
        public Bitmap photo;
        public Uri photoURI;
    }

2). get Contacts and convert to Model

     public List<ContactModel> getContacts(Context ctx) {
        List<ContactModel> list = new ArrayList<>();
        ContentResolver contentResolver = ctx.getContentResolver();
        Cursor cursor = contentResolver.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
        if (cursor.getCount() > 0) {
            while (cursor.moveToNext()) {
                String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
                if (cursor.getInt(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER)) > 0) {
                    Cursor cursorInfo = contentResolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
                            ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[]{id}, null);
                    InputStream inputStream = ContactsContract.Contacts.openContactPhotoInputStream(ctx.getContentResolver(),
                            ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, new Long(id)));

                    Uri person = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, new Long(id));
                    Uri pURI = Uri.withAppendedPath(person, ContactsContract.Contacts.Photo.CONTENT_DIRECTORY);

                    Bitmap photo = null;
                    if (inputStream != null) {
                        photo = BitmapFactory.decodeStream(inputStream);
                    }
                    while (cursorInfo.moveToNext()) {
                        ContactModel info = new ContactModel();
                        info.id = id;
                        info.name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
                        info.mobileNumber = cursorInfo.getString(cursorInfo.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                        info.photo = photo;
                        info.photoURI= pURI;
                        list.add(info);
                    }

                    cursorInfo.close();
                }
            }
            cursor.close();
        }
        return list;
    }

Upvotes: 18

Aerrow
Aerrow

Reputation: 12134

Try this too,

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

    if ((cur != null ? cur.getCount() : 0) > 0) {
        while (cur != null && cur.moveToNext()) {
            String id = cur.getString(
                    cur.getColumnIndex(ContactsContract.Contacts._ID));
            String name = cur.getString(cur.getColumnIndex(
                    ContactsContract.Contacts.DISPLAY_NAME));

            if (cur.getInt(cur.getColumnIndex(
                    ContactsContract.Contacts.HAS_PHONE_NUMBER)) > 0) {
                Cursor pCur = cr.query(
                        ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                        null,
                        ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
                        new String[]{id}, null);
                while (pCur.moveToNext()) {
                    String phoneNo = pCur.getString(pCur.getColumnIndex(
                            ContactsContract.CommonDataKinds.Phone.NUMBER));
                    Log.i(TAG, "Name: " + name);
                    Log.i(TAG, "Phone Number: " + phoneNo);
                }
                pCur.close();
            }
        }
    }
    if(cur!=null){
        cur.close();
    }
}

If you need more reference means refer this link Read ContactList

Upvotes: 202

Artyom
Artyom

Reputation: 1099

public class MyActivity extends Activity 
                        implements LoaderManager.LoaderCallbacks<Cursor> {

    private static final int CONTACTS_LOADER_ID = 1;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        // Prepare the loader.  Either re-connect with an existing one,
        // or start a new one.
        getLoaderManager().initLoader(CONTACTS_LOADER_ID,
                                      null,
                                      this);
    }

    @Override
    public Loader<Cursor> onCreateLoader(int id, Bundle args) {
        // This is called when a new Loader needs to be created.

        if (id == CONTACTS_LOADER_ID) {
            return contactsLoader();
        }
        return null;
    }

    @Override
    public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
        //The framework will take care of closing the
        // old cursor once we return.
        List<String> contacts = contactsFromCursor(cursor);
    }

    @Override
    public void onLoaderReset(Loader<Cursor> loader) {
        // This is called when the last Cursor provided to onLoadFinished()
        // above is about to be closed.  We need to make sure we are no
        // longer using it.
    }

    private  Loader<Cursor> contactsLoader() {
        Uri contactsUri = ContactsContract.Contacts.CONTENT_URI; // The content URI of the phone contacts

        String[] projection = {                                  // The columns to return for each row
                ContactsContract.Contacts.DISPLAY_NAME
        } ;

        String selection = null;                                 //Selection criteria
        String[] selectionArgs = {};                             //Selection criteria
        String sortOrder = null;                                 //The sort order for the returned rows

        return new CursorLoader(
                getApplicationContext(),
                contactsUri,
                projection,
                selection,
                selectionArgs,
                sortOrder);
    }

    private List<String> contactsFromCursor(Cursor cursor) {
        List<String> contacts = new ArrayList<String>();

        if (cursor.getCount() > 0) {
            cursor.moveToFirst();

            do {
                String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
                contacts.add(name);
            } while (cursor.moveToNext());
        }

        return contacts;
    }

}

and do not forget

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

Upvotes: 17

Related Questions