Read all contacts' phone numbers in android - android

I'm using this code to retrieve all contact names and phone numbers:
String[] projection = new String[]
{
People.NAME,
People.NUMBER
};
Cursor c = ctx.getContentResolver().query(People.CONTENT_URI, projection, null, null, People.NAME + " ASC");
c.moveToFirst();
int nameCol = c.getColumnIndex(People.NAME);
int numCol = c.getColumnIndex(People.NUMBER);
int nContacts = c.getCount();
do
{
// Do something
} while(c.moveToNext());
However, this will only return the primary number for each contact, but I want to get the secondary numbers as well. How can i do this?

Following code shows an easy way to read all phone numbers and names:
Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null, null);
while (phones.moveToNext())
{
String name=phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
}
phones.close();
NOTE: getContentResolver is a method from the Activity context.

You can read all of the telephone numbers associated with a contact in the following manner:
Uri personUri = ContentUris.withAppendedId(People.CONTENT_URI, personId);
Uri phonesUri = Uri.withAppendedPath(personUri, People.Phones.CONTENT_DIRECTORY);
String[] proj = new String[] {Phones._ID, Phones.TYPE, Phones.NUMBER, Phones.LABEL}
Cursor cursor = contentResolver.query(phonesUri, proj, null, null, null);
Please note that this example (like yours) uses the deprecated contacts API. From eclair onwards this has been replaced with the ContactsContract API.

This code shows how to get all phone numbers for each contact.
ContentResolver cr = getActivity().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) {
Cursor pCur = cr.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = ?",
new String[]{id}, null);
while (pCur.moveToNext()) {
int phoneType = pCur.getInt(pCur.getColumnIndex(
ContactsContract.CommonDataKinds.Phone.TYPE));
String phoneNumber = pCur.getString(pCur.getColumnIndex(
ContactsContract.CommonDataKinds.Phone.NUMBER));
switch (phoneType) {
case Phone.TYPE_MOBILE:
Log.e(name + "(mobile number)", phoneNumber);
break;
case Phone.TYPE_HOME:
Log.e(name + "(home number)", phoneNumber);
break;
case Phone.TYPE_WORK:
Log.e(name + "(work number)", phoneNumber);
break;
case Phone.TYPE_OTHER:
Log.e(name + "(other number)", phoneNumber);
break;
default:
break;
}
}
pCur.close();
}
}
}

In case it helps, I've got an example that uses the ContactsContract API to first find a contact by name, then it iterates through the details looking for specific number types:
How to use ContactsContract to retrieve phone numbers and email addresses

You can get all phone contacts using this:
Cursor c = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
new String[] { ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.NUMBER,
ContactsContract.RawContacts.ACCOUNT_TYPE },
ContactsContract.RawContacts.ACCOUNT_TYPE + " <> 'google' ",
null, null);
check complete example HERE...........

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 <span id="IL_AD4" class="IL_AD">phone
// number</span>
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();

Accepted answer working but not given unique numbers.
See this code, it return unique numbers.
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,
ContactsContract.CommonDataKinds.Phone.NUMBER,
ContactsContract.CommonDataKinds.Phone.NORMALIZED_NUMBER,
ContactsContract.Contacts.HAS_PHONE_NUMBER
};
Cursor phones = contentResolver
.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI
, fieldListProjection, null, null, null);
HashSet<String> normalizedNumbersAlreadyFound = new HashSet<>();
if (phones != null && phones.getCount() > 0) {
while (phones.moveToNext()) {
String normalizedNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NORMALIZED_NUMBER));
if (Integer.parseInt(phones.getString(phones.getColumnIndex(
ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
if (normalizedNumbersAlreadyFound.add(normalizedNumber)) {
String id = phones.getString(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));
Log.d("test", " Print all values");
}
}
}
phones.close();
}
}

In the same way just get their other numbers using the other "People" references
People.TYPE_HOME
People.TYPE_MOBILE
People.TYPE_OTHER
People.TYPE_WORK

This one finally gave me the answer I was looking for. It lets you retrieve all the names and phone numbers of the contacts on the phone.
package com.test;
import android.app.Activity;
import android.content.ContentResolver;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
public class TestContacts extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
null, null, null, null);
if (cur != null && cur.getCount() > 0) {
while (cur.moveToNext()) {
if (Integer.parseInt.equals(cur.getString(cur.getColumnIndex(
ContactsContract.Contacts.HAS_PHONE_NUMBER)))) {
String id = cur.getString(cur.getColumnIndex(
ContactsContract.Contacts._ID));
String name = cur.getString(cur.getColumnIndex(
ContactsContract.Contacts.DISPLAY_NAME));
Cursor pCur = cr.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID
+ " = ?", new String[] { id }, null);
int i = 0;
int pCount = pCur.getCount();
String[] phoneNum = new String[pCount];
String[] phoneType = new String[pCount];
while (pCur != null && pCur.moveToNext()) {
phoneNum[i] = pCur.getString(pCur.getColumnIndex(
ContactsContract.CommonDataKinds.Phone.NUMBER));
phoneType[i] = pCur.getString(pCur.getColumnIndex(
ContactsContract.CommonDataKinds.Phone.TYPE));
i++;
}
}
}
}
}
}

I fixed my need belove
manifest permissions
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.WRITE_CONTACTS"/>
<!-- Read Contacts from phone -->
<uses-permission android:name="android.permission.read_contacts" />
<uses-permission android:name="android.permission.read_phone_state" />
<uses-permission android:name="android.permission.READ_CALL_LOG" />
Note: After giving permissions at manifest some mobile phones can deny if so you need to go Settings--> Applications--> find your application click on it and
turn On the permissions needed
btn_readallcontacks.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
List<User> userList = new ArrayList<User>();
while (phones.moveToNext()) {
User user = new User();
user.setNamee(phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME)));
user.setPhone(phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)));
userList.add(user);
Log.d(TAG, "Name : " + user.getNamee().toString());
Log.d(TAG, "Phone : " + user.getPhone().toString());
}
phones.close();
}
});

You can get all the contact all those which have no number and all those which have no name from this piece of code
public void readContacts() {
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
null, null, null, ContactsContract.RawContacts.DISPLAY_NAME_PRIMARY + " ASC");
ContactCount = cur.getCount();
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));
String phone = null;
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()) {
phone = pCur.getString(
pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
System.out.println("phone" + phone);
}
pCur.close();
}
if (phone == "" || name == "" || name.equals(phone)) {
if (phone.equals(""))
getAllContact.add(new MissingPhoneModelClass("No Number", name, id));
if (name.equals("") || name.equals(phone))
getAllContact.add(new MissingPhoneModelClass(phone, "No Name", id));
} else {
if(TextUtils.equals(phone,null)){
getAllContact.add(new MissingPhoneModelClass("No Number", name, id));
}
else {
getAllContact.add(new MissingPhoneModelClass(phone, name, id));
}
}
}
}
}
One thing can be done you have to give the permission in the manifest for contact READ and WRITE
After that you can create the model class for the list which can be use to add all the contact here is the model class
public class PhoneModelClass {
private String number;
private String name;
private String id;
private String rawId;
public PhoneModelClass(String number, String name, String id, String rawId) {
this.number = number;
this.name = name;
this.id = id;
this.rawId = rawId;
}
public PhoneModelClass(String number, String name, String id) {
this.number = number;
this.name = name;
this.id = id;
}
public String getRawId() {
return rawId;
}
public void setRawId(String rawId) {
this.rawId = rawId;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
Enjoy :)

Load contacts in background using CursorLoader:
CursorLoader cursor = new CursorLoader(this, ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
Cursor managedCursor = cursor.loadInBackground();
int number = managedCursor.getColumnIndex(ContactsContract.Contacts.Data.DATA1);
int name = managedCursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
int index = 0;
while (managedCursor.moveToNext()) {
String phNumber = managedCursor.getString(number);
String phName = managedCursor.getString(name);
}

Here's how to use ContentsContract API to fetch your contacts in your Phone Book.
You'll need to add these permissions in your AndroidManifest.xml
<uses-permission android:name="android.permission.WRITE_CONTACTS" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
Then, you can run this method to loop through all your contacts.
Here's an example to query fields like Name and Phone Number, you can configure yourself to use CommonDataKinds, it query other fields in your Contact.
https://developer.android.com/reference/android/provider/ContactsContract.CommonDataKinds
private fun readContactsOnDevice() {
val context = requireContext()
if (ContextCompat.checkSelfPermission(
context, Manifest.permission.WRITE_CONTACTS
) != PackageManager.PERMISSION_GRANTED &&
ContextCompat.checkSelfPermission(
context, Manifest.permission.READ_CONTACTS
) != PackageManager.PERMISSION_GRANTED
) {
requestPermissions(
arrayOf(Manifest.permission.READ_CONTACTS, Manifest.permission.WRITE_CONTACTS), 1
)
return
}
val contentResolver = context.contentResolver
val contacts = contentResolver.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null, null, null, null
)
while (contacts?.moveToNext() == true) {
val name = contacts.getString(
contacts.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME)
)
val phoneNumber = contacts.getString(
contacts.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)
)
Timber.i("Name: $name, Phone Number: $phoneNumber")
}
}

package com.example.readcontacts;
import java.util.ArrayList;
import android.app.Activity; import android.app.ProgressDialog;
import android.content.ContentResolver; import
android.database.Cursor; import android.net.Uri; import
android.os.Bundle; import android.os.Handler; import
android.provider.ContactsContract; import android.view.View; import
android.widget.AdapterView; import
android.widget.AdapterView.OnItemClickListener; import
android.widget.ArrayAdapter; import android.widget.ListView; import
android.widget.Toast;
public class MainActivity extends Activity { private ListView
mListView; private ProgressDialog pDialog; private Handler
updateBarHandler;
ArrayList<String> contactList; Cursor cursor; int counter;
#Override public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pDialog = new ProgressDialog(this); pDialog.setMessage("Reading
contacts..."); pDialog.setCancelable(false); pDialog.show();
mListView = (ListView) findViewById(R.id.list); updateBarHandler
=new Handler();
// Since reading contacts takes more time, let's run it on a separate thread. new Thread(new Runnable() {
#Override public void run() {
getContacts(); } }).start();
// Set onclicklistener to the list item.
mListView.setOnItemClickListener(new OnItemClickListener() {
#Override public void onItemClick(AdapterView<?> parent, View
view,
int position, long id) {
//TODO Do whatever you want with the list data
Toast.makeText(getApplicationContext(), "item clicked : \n"+contactList.get(position), Toast.LENGTH_SHORT).show(); }
}); }
public void getContacts() {
contactList = new ArrayList<String>();
String phoneNumber = null; String email = null;
Uri CONTENT_URI = ContactsContract.Contacts.CONTENT_URI; String
_ID = ContactsContract.Contacts._ID; String DISPLAY_NAME = ContactsContract.Contacts.DISPLAY_NAME; String HAS_PHONE_NUMBER =
ContactsContract.Contacts.HAS_PHONE_NUMBER;
Uri PhoneCONTENT_URI =
ContactsContract.CommonDataKinds.Phone.CONTENT_URI; String
Phone_CONTACT_ID =
ContactsContract.CommonDataKinds.Phone.CONTACT_ID; String NUMBER =
ContactsContract.CommonDataKinds.Phone.NUMBER;
Uri EmailCONTENT_URI =
ContactsContract.CommonDataKinds.Email.CONTENT_URI; String
EmailCONTACT_ID = ContactsContract.CommonDataKinds.Email.CONTACT_ID;
String DATA = ContactsContract.CommonDataKinds.Email.DATA;
StringBuffer output;
ContentResolver contentResolver = getContentResolver();
cursor = contentResolver.query(CONTENT_URI, null,null, null,
null);
// Iterate every contact in the phone if (cursor.getCount() > 0)
{
counter = 0; while (cursor.moveToNext()) {
output = new StringBuffer();
// Update the progress message
updateBarHandler.post(new Runnable() {
public void run() {
pDialog.setMessage("Reading contacts : "+ counter++ +"/"+cursor.getCount());
}
});
String contact_id = cursor.getString(cursor.getColumnIndex( _ID ));
String name = cursor.getString(cursor.getColumnIndex( DISPLAY_NAME ));
int hasPhoneNumber = Integer.parseInt(cursor.getString(cursor.getColumnIndex(
HAS_PHONE_NUMBER )));
if (hasPhoneNumber > 0) {
output.append("\n First Name:" + name);
//This is to read multiple phone numbers associated with the same contact
Cursor phoneCursor = contentResolver.query(PhoneCONTENT_URI, null, Phone_CONTACT_ID + " = ?", new String[] { contact_id }, null);
while (phoneCursor.moveToNext()) {
phoneNumber = phoneCursor.getString(phoneCursor.getColumnIndex(NUMBER));
output.append("\n Phone number:" + phoneNumber);
}
phoneCursor.close();
// Read every email id associated with the contact
Cursor emailCursor = contentResolver.query(EmailCONTENT_URI, null, EmailCONTACT_ID+ " =
?", new String[] { contact_id }, null);
while (emailCursor.moveToNext()) {
email = emailCursor.getString(emailCursor.getColumnIndex(DATA));
output.append("\n Email:" + email);
}
emailCursor.close();
}
// Add the contact to the ArrayList
contactList.add(output.toString()); }
// ListView has to be updated using a ui thread
runOnUiThread(new Runnable() {
#Override
public void run() {
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(), R.layout.list_item,
R.id.text1, contactList);
mListView.setAdapter(adapter);
} });
// Dismiss the progressbar after 500 millisecondds
updateBarHandler.postDelayed(new Runnable() {
#Override
public void run() {
pDialog.cancel();
} }, 500); }
}
}
List item

Code to get contact name (Ascending order) and number
For more reference: show contact in listview
Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME+" ASC");
while (phones.moveToNext())
{
String name=phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
}
phones.close();

Related

Android: how do I get a number from Contacts by email?

My goal is to get the phone number and the e-mail of a contact.
I've tried to use one cursor but somehow it returns the same thing for phone and e-mail (either of the two, depending on tweaking some things). What I want right now is a hashtable that maps e-mails to phone numbers, or two hashtables, emailToID, and IDToPhone. This is what I have so far, but the IDs I use are not the same accross parameters (the a#a.com's phone is 123, their respective IDs are not the same and cannot be easily mapped). Would be grateful for help!
public String getPhoneByEmail(String userEmail){
final String EMAIL_URI = ContactsContract.CommonDataKinds.Email.DATA;
final String PHONE_URI = ContactsContract.CommonDataKinds.Phone.NUMBER;
Hashtable<String, Integer> emailToId = new Hashtable<>();
Hashtable<Integer, String> idToPhone = new Hashtable<>();
ContentResolver cr = getContext().getContentResolver();
Cursor cur1 = cr.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
null,
null, null);
Cursor cur2 = cr.query(
ContactsContract.CommonDataKinds.Email.CONTENT_URI, null,
null,
null, null);
while (cur1.moveToNext()) {
String phone = cur1.getString(cur1.getColumnIndex(PHONE_URI));
String id1 = cur1.getString(cur1.getColumnIndex(ContactsContract.CommonDataKinds.Phone._ID));
idToPhone.put(Integer.parseInt(id1), phone);
}
while (cur2.moveToNext()) {
String email = cur2.getString(cur2.getColumnIndex(EMAIL_URI));
String id2 = cur2.getString(cur2.getColumnIndex(ContactsContract.CommonDataKinds.Email._ID));
emailToId.put(email, Integer.parseInt(id2));
}
cur1.close();
cur2.close();
if (emailToId.get(userEmail)!=null){
int id = emailToId.get(userEmail);
int newId = id - 2;
String phone = idToPhone.get(newId);
return phone;
}
else return "not found";
}
Got it with help from this: https://stackoverflow.com/a/4154729/6463084
private String getPhoneByEmail(String userEmail) {
Hashtable<String, String> emailToId = new Hashtable<>();
Hashtable<String, String> idToPhone = new Hashtable<>();
ContentResolver cr = getContext().getContentResolver();
Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
while (cursor.moveToNext()) {
String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
String name = cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_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 = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + contactId, null, null);
while (phones.moveToNext()) {
String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
idToPhone.put(contactId, phoneNumber);
}
phones.close();
}
Cursor emails = cr.query(ContactsContract.CommonDataKinds.Email.CONTENT_URI, null, ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = " + contactId, null, null);
while (emails.moveToNext()) {
String emailAddress = emails.getString(emails.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
emailToId.put(emailAddress, contactId);
}
emails.close();
}
cursor.close();
if (emailToId.get(userEmail) != null) {
String id = emailToId.get(userEmail);
if (idToPhone.get(id) != null) {
String phone = idToPhone.get(id);
return phone;
}
}
return "not found";
}
Try this code to Read Contact Number/Name/Email From Phone..
public void storeContactsInLocal() {
String sortOrder = ContactsContract.Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC";
// retrieve all contacts as a cursor.
Cursor cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, sortOrder);
//now we have cusror with contacts and get diffrent value from cusror.
String lastNumber = null;
while (cursor.moveToNext()) {
String name = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumber = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
String email = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
String number = phoneNumber.replaceAll("\\s+", "");
if (!number.equals(lastNumber)) {
lastNumber = number;
try {
// Save Contact in Database!
String contactDetail = "Name :" + name + " : " + "Number :" + number+ " : " + "Email :" + email;
Log.e("Contact :", contactDetail);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
Now call this Function from Your Activity like..
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Thread t = new Thread(new Runnable() {
#Override
public void run() {
storeContactsInLocal();
}
});
t.start();
}
}, 100);
Just don't forget to ask/Add Permission to read Contacts!

Unable to fetch contact names

I am trying this code to retrieve the contact numbers and contact names. I got the numbers but the Names list returns null
ContentResolver cr = this.getContentResolver(); //Activity/Application android.content.Context
Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
if(cursor.moveToFirst())
{
List<String> ContactNames = new ArrayList<String>();
do
{
String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
if(Integer.parseInt(cursor.getString(cursor.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 contactNumber = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
String contactNames = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
ContactNames.add(contactNames);
break;
}
pCur.close();
}
} while (cursor.moveToNext()) ;
}
I don't know what I am missing. Please help
Read Contact List from Phone:
import java.util.ArrayList;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Email;
public class ContactsUtils {
public static ArrayList<ContactModel> getContactList(Context ctx) {
ArrayList<ContactModel> list = new ArrayList<ContactModel>();
String displayName = "", phoneNo = "", email = " ";
ContentResolver contentResolver = ctx.getContentResolver();
Cursor curMain = contentResolver.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
if (curMain.getCount() > 0) {
while (curMain.moveToNext()) {
String contactId = curMain.getString(curMain.getColumnIndex(ContactsContract.Contacts._ID));
displayName = curMain.getString(curMain.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
if (Integer.parseInt(curMain.getString(curMain.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
Cursor phoneCursor = contentResolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = ?",new String[]{contactId}, null);
contentResolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null,ContactsContract.CommonDataKinds.Phone.CONTACT_ID+ " = ?", new String[] { contactId }, null);
Cursor emailCursor = contentResolver.query(Email.CONTENT_URI, null,Email.CONTACT_ID + " = " + contactId, null, null);
if(emailCursor.getCount()>0){
while (emailCursor.moveToNext()) {
email = emailCursor.getString(emailCursor.getColumnIndex(Email.DATA));
}
}else{
email = "";
}
emailCursor.close();
if(phoneCursor.getCount()>0){
while (phoneCursor.moveToNext()) {
phoneNo = phoneCursor.getString(phoneCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
}
}else{
phoneNo = "";
}
phoneCursor.close();
ContactModel cm = new ContactModel();
cm.setDisplayName(displayName);
cm.setPhoneNumber(phoneNo);
cm.setEmail(email);
list.add(cm);
}
}
}
curMain.close();
return list;
}
public static class ContactModel implements Comparable<ContactModel>{
private String displayName = "", phoneNumber = "", email = "";
#Override
public int compareTo(ContactModel another) {
return getDisplayName().compareTo(another.getDisplayName());
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getDisplayName() {
return displayName;
}
public void setDisplayName(String displayName) {
this.displayName = displayName;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public ContactModel() {
}
public ContactModel(String name) {
this.displayName = name;
}
public String toString() {
return displayName;
}
}
}
Add permission in Manifest file:
<uses-permission android:name="android.permission.READ_CONTACTS"/>
Hope it will help you.

android get contacts detail such as number and thumbnail

i use of this code that can get contact's number and contact's thumbnail , but this is not suitable and take to long to load and prepare contacts .
please help me to improve performance of this code :
List<Contact_Pojo> list = new ArrayList<Contact_Pojo>();
ContentResolver cr = getActivity().getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null,
null, null, Phone.DISPLAY_NAME + " ASC");
int i = 0;
if (cur.moveToFirst()) {
while (cur.moveToNext()) {
Cursor phoneCursor = getActivity()
.getContentResolver()
.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
new String[] { ContactsContract.CommonDataKinds.Phone.NUMBER, },
ContactsContract.CommonDataKinds.Phone.CONTACT_ID
+ " = ?",
new String[] { cur.getString(cur
.getColumnIndex(ContactsContract.Contacts._ID)) },
null);
if (phoneCursor.moveToFirst()) {
Contact_Pojo personContact = new Contact_Pojo();
/*
* Id
*/
personContact.setId(cur.getString(1));
/*
* Name
*/
personContact
.setName(cur.getString(cur
.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)));
/*
* Photo ID
*/
personContact
.setImageUrl(cur.getString(cur
.getColumnIndex(ContactsContract.Contacts.PHOTO_THUMBNAIL_URI)));
/*
* Number
*/
personContact.setNumber(phoneCursor.getString(0));
//
list.add(personContact);
}
phoneCursor.close();
}
}
cur.close();
return list;
Update 4/4/2015
it is slow because it has getting all column from contact provider , in this table has +20 column that take many time .
How about using AsyncTaskLoader,
write this code when you want to get contacts list
getLoaderManager() or getSupportLoaderManager().initLoader(int id, Bundle args, LoaderManager.LoaderCallbacks<D> loadingCallback)
public class LoadingCallback implements LoaderManager.LoaderCallbacks<Void> {
#Override
public Loader<Void> onCreateLoader(int i, Bundle bundle) {
// Show your dialog;
return new InitializeContactsTask(context, (ArrayList) contactList, mAdapter);
}
#Override
public void onLoadFinished(Loader<Void> voidLoader, Void aVoid) {
// UI Work here after background task and hide dialog.
}
#Override
public void onLoaderReset(Loader<Void> voidLoader) {
}
}
and
public class InitializeApplicationsTask extends AsyncTaskLoader<Void> {
#Override
protected void onStartLoading() {
forceLoad();
}
#Override
public Void loadInBackground() {
// Query the contacts here and return null
return null;
}
}
It's slow because, you are getting all column from contact provider, so use projection to get only those column which are required. like
String[] projection = {
ContactsContract.Contacts.DISPLAY_NAME
// this is just example, add fields that required
} ;
can you please tell me what is purpose of second query ? because here is my result of getting contact
and my method for getting all contact is
#SuppressLint("InlinedApi")
public void readContacts() {
long l1 = System.currentTimeMillis();
Log.d("DEBUG",
"starting readContacts() time " + l1);
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null,
null, null, null);
if (cur.getCount() > 0) {
while (cur.moveToNext()) {
Contact_pojo cp = new Contact_pojo();
String Contact_Id = cur.getString(cur
.getColumnIndex(ContactsContract.Contacts._ID));
String Contact_Name = cur
.getString(cur
.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
String photothumb = "";
try {
photothumb = cur
.getString(cur
.getColumnIndex(ContactsContract.Contacts.PHOTO_THUMBNAIL_URI));
if (photothumb != null
&& !photothumb.toString().equalsIgnoreCase("")) {
cp.setImageUri(photothumb);
}
} catch (Exception e) {
e.printStackTrace();
}
cp.setId(Contact_Id);
cp.setName(Contact_Name);
Cursor phones = cr.query(Phone.CONTENT_URI, null,
Phone.CONTACT_ID + " = " + Contact_Id, null, null);
while (phones.moveToNext()) {
String number = phones.getString(phones
.getColumnIndex(Phone.NUMBER));
int type = phones.getInt(phones.getColumnIndex(Phone.TYPE));
Log.d("DEBUG", "number " + number + " type " + type);
cp.setNumber(number);
}
phones.close();
contactList.add(cp);
}
}
long l2 = System.currentTimeMillis();
Log.d("DEBUG",
"Finished readContacts() time " + l2);
Log.d("DEBUG","Total contact loaded "+contactList.size()+" within "+ (l2 - l1) + "ms");
}
Don't use double query, this is taking too much time if device have lots of contacts and it's not working in some device also...
You can also fetch contact with single query..
Use below code..
public void fetchContacts()
{
String[] projection = new String[] {
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.HAS_PHONE_NUMBER,
ContactsContract.CommonDataKinds.Phone.NUMBER,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID};
String _ID = ContactsContract.CommonDataKinds.Phone.CONTACT_ID;
String DISPLAY_NAME = Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB ? Contacts.DISPLAY_NAME_PRIMARY : Contacts.DISPLAY_NAME;
String NUMBER = ContactsContract.CommonDataKinds.Phone.NUMBER;
Cursor cursor = mActivity.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
projection, ContactsContract.CommonDataKinds.Phone.HAS_PHONE_NUMBER + "=?", new String[] { "1" },
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
System.out.println("contact size.."+cursor.getCount());
if (cursor.getCount() > 0) {
while (cursor.moveToNext()) {
String contact_id = cursor.getString(cursor.getColumnIndex( _ID ));
String name = cursor.getString(cursor.getColumnIndex( DISPLAY_NAME ));
String phoneNumber = cursor.getString(cursor.getColumnIndex(NUMBER));
System.out.println(" name : "+name);
System.out.println(" number : "+phoneNumber);
}
}
}
Check below links for get contact photo.
ContactsContract.Contacts.Photo
Getting a Photo from a Contact

how to display the phone contacts?

i am getting the phone no,mail, name from contacts and stored in side the 3array list, display the contacts.
the contacts are stored in side the array list sequentially.
if i store a contact contains phone no,name and with out mail id.
i want to store the mail id null in side the mails array list.
if any one has solution please help me.
Thanks in advance.
Main Activity how can retrieve data...
public class AddressBook extends Activity
{
ListView lv1;
String[] row,row1;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//how can retrieve contact details ...................................................
ContactList1.getContactEmails(this,emailContacts1);
ContactList1.getContactNumbers(this,phoneContacts1);
how can implemented the code.......................................
}
}
Try with the following approach
Try to create a bean where you will store details and create an arraylist of that bean class
AddressBook.java
import java.util.ArrayList;
import java.util.Iterator;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.provider.BaseColumns;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Email;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
public class AddressBook extends Activity
{
ListView lv1;
String[] row,row1;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ArrayList<ContactEmailBean> emailContacts1 = getContactEmails(this);
ArrayList<ContactNumberBean> phoneContacts1 = getContactNumbers(this);
}
public ArrayList<ContactNumberBean> getContactNumbers(Context context) {
String contactNumber = null;
int contactNumberType = Phone.TYPE_MOBILE;
String nameOfContact = null;
ArrayList<ContactNumberBean> phoneContacts = new ArrayList<ContactNumberBean>();
ContentResolver cr = context.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(BaseColumns._ID));
nameOfContact = cur
.getString(cur
.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
if (Integer
.parseInt(cur.getString(cur
.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
Cursor phones = cr
.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID
+ " = ?", new String[] { id },
null);
while (phones.moveToNext()) {
contactNumber = phones.getString(phones
.getColumnIndex(Phone.NUMBER));
contactNumberType = phones.getInt(phones
.getColumnIndex(Phone.TYPE));
phoneContacts
.add(new ContactNumberBean(nameOfContact,
contactNumber, contactNumberType));
}
phones.close();
}
}
}// end of contact name cursor
cur.close();
return phoneContacts;
}
/**
*
* This method is responsible to get native contacts and corresponding email
* id (ApplicationConstants.emailContacts)
*
* #param context
*/
public ArrayList<ContactEmailBean> getContactEmails(Context context) {
String emailIdOfContact = null;
int emailType = Email.TYPE_WORK;
String contactName = null;
ArrayList<ContactEmailBean> emailContacts = new ArrayList<ContactEmailBean>();
ContentResolver cr = context.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(BaseColumns._ID));
contactName = cur
.getString(cur
.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
// Log.i(TAG,"....contact name....." +
// contactName);
cr.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID
+ " = ?", new String[] { id }, null);
Cursor emails = cr.query(Email.CONTENT_URI, null,
Email.CONTACT_ID + " = " + id, null, null);
while (emails.moveToNext()) {
emailIdOfContact = emails.getString(emails
.getColumnIndex(Email.DATA));
// Log.i(TAG,"...COntact Name ...."
// + contactName + "...contact Number..."
// + emailIdOfContact);
emailType = emails.getInt(emails
.getColumnIndex(Phone.TYPE));
emailContacts
.add(new ContactEmailBean(contactName,
emailIdOfContact, emailType));
}
emails.close();
}
}// end of contact name cursor
cur.close();
return emailContacts;
}
}
here Class B does not extends Activity.
But write the following method to gwt contacts and email id in class B
public static void getContactNumbers(Context context) {
String contactNumber = null;
int contactNumberType = Phone.TYPE_MOBILE;
String nameOfContact = null;
ArrayList<ContactNumberBean> phoneContacts = new ArrayList<ContactNumberBean>();
ContentResolver cr = context.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(BaseColumns._ID));
nameOfContact = cur
.getString(cur
.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
if (Integer
.parseInt(cur.getString(cur
.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
Cursor phones = cr
.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID
+ " = ?", new String[] { id },
null);
while (phones.moveToNext()) {
contactNumber = phones.getString(phones
.getColumnIndex(Phone.NUMBER));
contactNumberType = phones.getInt(phones
.getColumnIndex(Phone.TYPE));
phoneContacts
.add(new ContactNumberBean(nameOfContact,
contactNumber, contactNumberType));
}
phones.close();
}
}
}// end of contact name cursor
cur.close();
}
/**
*
* This method is responsible to get native contacts and corresponding email
* id (ApplicationConstants.emailContacts)
*
* #param context
*/
public static void getContactEmails(Context context) {
String emailIdOfContact = null;
int emailType = Email.TYPE_WORK;
String contactName = null;
ArrayList<ContactEmailBean> emailContacts = new ArrayList<ContactEmailBean>();
ContentResolver cr = context.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(BaseColumns._ID));
contactName = cur
.getString(cur
.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
// Log.i(TAG,"....contact name....." +
// contactName);
cr.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID
+ " = ?", new String[] { id }, null);
Cursor emails = cr.query(Email.CONTENT_URI, null,
Email.CONTACT_ID + " = " + id, null, null);
while (emails.moveToNext()) {
emailIdOfContact = emails.getString(emails
.getColumnIndex(Email.DATA));
// Log.i(TAG,"...COntact Name ...."
// + contactName + "...contact Number..."
// + emailIdOfContact);
emailType = emails.getInt(emails
.getColumnIndex(Phone.TYPE));
emailContacts
.add(new ContactEmailBean(contactName,
emailIdOfContact, emailType));
}
emails.close();
}
}// end of contact name cursor
cur.close();
}
Write two bean class
EmailBean
public class ContactEmailBean {
String emailType = null;
String nameOfContact = null;
String emailIdOfContact = null;
public ContactEmailBean(String nameOfContact, String emailIdOfContact,
int emailType) {
switch (emailType) {
case Email.TYPE_HOME:
this.emailType = "HOME";
// do something with the Home number here...
break;
case Email.TYPE_MOBILE:
this.emailType = "MOBILE";
// do something with the Mobile number here...
break;
case Email.TYPE_WORK:
this.emailType = "WORK";
// do something with the Work number here...
break;
default:
this.emailType = "OTHER";
break;
}
this.nameOfContact = nameOfContact;
this.emailIdOfContact = emailIdOfContact;
}
public String getNameOfContact() {
return this.nameOfContact;
}
public String getEmailType() {
return this.emailType;
}
public String getEmailIdOfContact() {
return this.emailIdOfContact;
}
}
ContactNumberBean
public class ContactNumberBean {
String phoneNumberType = null;
String nameOfContact = null;
String contactNumber = null;
public ContactNumberBean(String nameOfContact, String contactNumber,
int contactNumberType) {
switch (contactNumberType) {
case Phone.TYPE_HOME:
this.phoneNumberType = "HOME";
// do something with the Home number here...
break;
case Phone.TYPE_MOBILE:
this.phoneNumberType = "MOBILE";
// do something with the Mobile number here...
break;
case Phone.TYPE_WORK:
this.phoneNumberType = "WORK";
// do something with the Work number here...
break;
case Phone.TYPE_WORK_MOBILE:
this.phoneNumberType = "WORK";
break;
case Phone.TYPE_FAX_HOME:
this.phoneNumberType = "FAX";
break;
default:
this.phoneNumberType = "OTHER";
break;
}
this.nameOfContact = nameOfContact;
this.contactNumber = contactNumber;
}
public String getNameOfContact() {
return this.nameOfContact;
}
public String getPhoneNumberType() {
return this.phoneNumberType;
}
public String getContactNumber() {
return this.contactNumber;
}
}
Thanks
Deepak

How to get contacts from native phonebook in android

I want to display all native contacts in a list and make user to add contacts from the list (Multiple contacts)to my application database.How to dothis can any one give me idea or share some code..
thanks in advance..
I used this code on Android 2.1. It pulls down anyone who has a phone number (as defined by the String SELECTION variable) and returns a List of type Person. Person is an object that held the name and phone number of the user. You will have to implement a Person object in order to use this code, but it works perfectly:
public List<Person> getContactList(){
ArrayList<Person> contactList = new ArrayList<Person>();
Uri contactUri = ContactsContract.Contacts.CONTENT_URI;
String[] PROJECTION = new String[] {
ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.Contacts.HAS_PHONE_NUMBER,
};
String SELECTION = ContactsContract.Contacts.HAS_PHONE_NUMBER + "='1'";
Cursor contacts = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, PROJECTION, SELECTION, null, null);
if (contacts.getCount() > 0)
{
while(contacts.moveToNext()) {
Person aContact = new Person();
int idFieldColumnIndex = 0;
int nameFieldColumnIndex = 0;
int numberFieldColumnIndex = 0;
String contactId = contacts.getString(contacts.getColumnIndex(ContactsContract.Contacts._ID));
nameFieldColumnIndex = contacts.getColumnIndex(PhoneLookup.DISPLAY_NAME);
if (nameFieldColumnIndex > -1)
{
aContact.setName(contacts.getString(nameFieldColumnIndex));
}
PROJECTION = new String[] {Phone.NUMBER};
final Cursor phone = managedQuery(Phone.CONTENT_URI, PROJECTION, Data.CONTACT_ID + "=?", new String[]{String.valueOf(contactId)}, null);
if(phone.moveToFirst()) {
while(!phone.isAfterLast())
{
numberFieldColumnIndex = phone.getColumnIndex(Phone.NUMBER);
if (numberFieldColumnIndex > -1)
{
aContact.setPhoneNum(phone.getString(numberFieldColumnIndex));
phone.moveToNext();
TelephonyManager mTelephonyMgr;
mTelephonyMgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
if (!mTelephonyMgr.getLine1Number().contains(aContact.getPhoneNum()))
{
contactList.add(aContact);
}
}
}
}
phone.close();
}
contacts.close();
}
return contactList;
}
EDIT: A rudimentary Person class:
public class Person {
String myName = "";
String myNumber = "";
public String getName() {
return myName;
}
public void setName(String name) {
myName = name;
}
public String getPhoneNum() {
return myNumber;
}
public void setPhoneNum(String number) {
myNumber = number;
}
}
This code works perfectly in android 4.2. And it works much faster, because you don't make additional query for each contact
private static final String CONTACT_ID = ContactsContract.Contacts._ID;
private static final String DISPLAY_NAME = ContactsContract.Contacts.DISPLAY_NAME;
private static final String HAS_PHONE_NUMBER = ContactsContract.Contacts.HAS_PHONE_NUMBER;
private static final String PHONE_NUMBER = ContactsContract.CommonDataKinds.Phone.NUMBER;
private static final String PHONE_CONTACT_ID = ContactsContract.CommonDataKinds.Phone.CONTACT_ID;
public static ArrayList<Contact> getAll(Context context) {
ContentResolver cr = context.getContentResolver();
Cursor pCur = cr.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
new String[]{PHONE_NUMBER, PHONE_CONTACT_ID},
null,
null,
null
);
if(pCur != null){
if(pCur.getCount() > 0) {
HashMap<Integer, ArrayList<String>> phones = new HashMap<>();
while (pCur.moveToNext()) {
Integer contactId = pCur.getInt(pCur.getColumnIndex(PHONE_CONTACT_ID));
ArrayList<String> curPhones = new ArrayList<>();
if (phones.containsKey(contactId)) {
curPhones = phones.get(contactId);
}
curPhones.add(pCur.getString(pCur.getColumnIndex(PHONE_CONTACT_ID)));
phones.put(contactId, curPhones);
}
Cursor cur = cr.query(
ContactsContract.Contacts.CONTENT_URI,
new String[]{CONTACT_ID, DISPLAY_NAME, HAS_PHONE_NUMBER},
HAS_PHONE_NUMBER + " > 0",
null,
DISPLAY_NAME + " ASC");
if (cur != null) {
if (cur.getCount() > 0) {
ArrayList<Contact> contacts = new ArrayList<>();
while (cur.moveToNext()) {
int id = cur.getInt(cur.getColumnIndex(CONTACT_ID));
if(phones.containsKey(id)) {
Contact con = new Contact();
con.setMyId(id);
con.setName(cur.getString(cur.getColumnIndex(DISPLAY_NAME)));
con.setPhone(TextUtils.join(",", phones.get(id).toArray()));
contacts.add(con);
}
}
return contacts;
}
cur.close();
}
}
pCur.close();
}
return null;
}
Class Contact is similar to class Person from the answer.

Categories

Resources