I am making a small app where I can get the contacts of my phone using a content provider and display them in a listview as illustrated.
I want to select a row of the listview and automically make a phone call to that specific contact. I tried some things,but they don't work. Any ideas? Here is my code.
public class MainActivity extends ListActivity implements AdapterView.OnItemClickListener{
ArrayAdapter<String> adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ContentResolver cr = getContentResolver();
Cursor c = cr.query(ContactsContract.Contacts.CONTENT_URI,
new String[] {ContactsContract.Contacts.DISPLAY_NAME},
null, null, null);
List<String> contacts = new ArrayList<String>();
if (c.moveToFirst()) {
do {
contacts.add(c.getString(c.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)));
} while (c.moveToNext());
}
adapter = new ArrayAdapter<String>(this, R.layout.activity_main, contacts);
setListAdapter(adapter);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//The answer should be inside here.
}
}
First, ensure that you have added the Permission to your AndroidManifest.xml file:
<uses-permission android:name="android.permission.READ_CONTACTS"/>
UPDATE:
On Android 6 and higher stating the permission in the manifest is not enough, you have to explicitly ask user for granting permission on reading contacts otherwise, you will get an exception. See this answer for more details.
Then you can loop through your phone contacts like this:
Cursor cursor = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI,null, null, null, null);
while (cursor.moveToNext()) {
String contactId = cursor.getString(cursor.getColumnIndex(
String hasPhone = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
if (Boolean.parseBoolean(hasPhone)) {
// You know it has a number so now query it like this
Cursor phones = getContentResolver().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));
}
phones.close();
}
Cursor emails = getContentResolver().query(ContactsContract.CommonDataKinds.Email.CONTENT_URI, null, ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = " + contactId, null, null);
while (emails.moveToNext()) {
// This would allow you get several email addresses
String emailAddress = emails.getString(
emails.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
}
emails.close();
}
Try with:
private void doMagicContacts() {
Cursor cursor = getContentResolver()
.query(ContactsContract.Contacts.CONTENT_URI,
null,
null,
null,
null);
if (cursor == null) {
return;
}
cursor.moveToFirst();
do {
String name = cursor.getString(
cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
String id = cursor.getString(
cursor.getColumnIndex(ContactsContract.Contacts.NAME_RAW_CONTACT_ID));
Cursor phones = getContentResolver()
.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.RAW_CONTACT_ID+" = " + id,
null,
null);
if (phones != null) {
while (phones.moveToNext()) {
String phoneNumber = phones.getString(
phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
Log.d(TAG, "doMagicContacts: " + name + " " + phoneNumber);
}
phones.close();
}
} while (cursor.moveToNext());
cursor.close();
}
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
I want to get all contact in local address book of Android device by Group Name. Such as "Family", "Friends", "Work" ... like Address book in android device.
Here is my code:
public void getAllContactsByGroup(ContentResolver cr) {
String a = "Friends";
Uri CONTENT_URI_GR = ContactsContract.Groups.CONTENT_URI;
String GR_ID = ContactsContract.Groups._ID;
String GR_NAME = ContactsContract.Groups.TITLE;
Cursor cursor = getContentResolver().query(CONTENT_URI_GR,
null, GR_NAME + "=?", new String[] { a }, null);
while (cursor.moveToNext())
{
Uri CONTENT_URI = ContactsContract.Contacts.CONTENT_URI;
String _ID = ContactsContract.Contacts._ID;
String DISPLAY_NAME = ContactsContract.Contacts.DISPLAY_NAME;
Cursor phones = cr.query(CONTENT_URI, null, null, null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC");
countContact = phones.getCount();
while (phones.moveToNext())
{
contact_id = phones.getString(phones.getColumnIndex(_ID));
String name = phones.getString(phones.getColumnIndex(DISPLAY_NAME));
name1.add(name);
_idd.add(contact_id);
}
phones.close();
}
cursor.close();
}
I tried to get all contact in group "Friends" of Address book, but it gets all contacts of all groups.
try
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Cursor cur = getContacts();
ListView lv = getListView();
String[] fields = new String[] {ContactsContract.Data.DISPLAY_NAME};
SimpleCursorAdapter adapter =
new SimpleCursorAdapter(this,
R.layout.main,
cur,
fields,
new int[] {R.id.txtbox});
lv.setAdapter(adapter);
}
private Cursor getContacts() {
// Run query
Uri uri = ContactsContract.Contacts.CONTENT_URI;
String[] projection =
new String[]{ ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME };
String selection = null;
String[] selectionArgs = null;
String sortOrder = ContactsContract.Contacts.DISPLAY_NAME +
" COLLATE LOCALIZED ASC";
return managedQuery(uri, projection, selection, selectionArgs, sortOrder);
}
I have this method to display the contact numbers in my inbox:
public ArrayList<String> fetchInboxNumbers() {
ArrayList<String> sms = new ArrayList<String>();
Uri uriSms = Uri.parse("content://sms/inbox");
Cursor cursor = getContentResolver().query(uriSms,
new String[] { "_id", "address", "date", "body" }, null, null, null);
cursor.moveToFirst();
while (cursor.moveToNext()) {
address = cursor.getString(1); // Displays phone number
Log.d("CONTACT", address);
sms.add(address); // + " " + body
}
Log.d("NAMES IN CALLLOG", sms.get(7));
return sms;
} // END FETCHINBOX
What I'm trying to do is change String address to its contact name.
From fetchContactNumbers() and 'fetchContactNames(), how can I changeaddress` to a contact name?
Its important to understand that fetchContactNumbers and fetchContactNames() are aligned, meaning fetchContactNumbers().get(5)'s contact name is fetchContactNames().get(5)`.
In the end, fetchInboxNumbers() populates a custom adapter.
This method returns a list of all contact names:
public ArrayList<String> fetchContactNames() {
ArrayList<String> names = new ArrayList<String>();
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));
names.add(name);
}
phones.close();
return names;
}
And this method lists all phone numbers:
public ArrayList<String> fetchContactNumbers() {
ArrayList<String> numbers = new ArrayList<String>();
Cursor phones = getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null,
null, null);
while (phones.moveToNext()) {
String phoneNumber = phones
.getString(phones
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
numbers.add(phoneNumber);
}
phones.close();
return numbers;
}
You can use CONTENT_FILTER_URI to get the display name, instead of getting all names and numbers separately, something like below:
public ArrayList<String> fetchInboxNumbers() {
String displayName = "";
ArrayList<String> sms = new ArrayList<String>();
Uri uriSms = Uri.parse("content://sms/inbox");
Cursor cursor = getContentResolver().query(uriSms,
new String[] { "_id", "address", "date", "body" }, null, null, null);
cursor.moveToFirst();
while (cursor.moveToNext()) {
address = cursor.getString(1); // Displays phone number
displayName = getDisplayName(address);
sms.add(displayName); // + " " + body
}
return sms;
} // END FETCHINBOX
private String getDisplayName(String phoneNumber) {
String displayName = "";
Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phoneNumber));
Cursor cursor = context.getContentResolver().query(uri, new String[] { Phone._ID, Phone.DISPLAY_NAME}, null, null, null);
if (cursor.moveToFirst()) {
displayName = cursor.getString(cursor.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME));
}
return displayName;
}
Is it a spelling mistake? a variable mistake?
private String getDisplayName(String phoneNyumber) {
Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.
CONTENT_FILTER_URI, Uri.encode(phoneNumber));
.....
}
Your argument is having phoneNyumber and you are using phoneNumber.
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();