I want to get the contact's(Saved in phonebook) mobile number, work number and home number. I want to set these numbers in my 3 edittext views. How to do this? Here is my code
Cursor phones = getActivity().getContentResolver().query(
Phone.CONTENT_URI,
null,
Phone.CONTACT_ID + " = " + phoneId,
null,
null
);
while (phones.moveToNext()) {
number = phones.getString(phones.getColumnIndex(Phone.NUMBER));
int type = phones.getInt(phones.getColumnIndex(Phone.TYPE));
if (type == Phone.TYPE_HOME) {
number = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DATA));
return number;
}
if (type == Phone.TYPE_MOBILE) {
number = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DATA));
return number;
}
if (type == Phone.TYPE_WORK) {
number = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DATA));
return number;
}
}
try this link to get the contact details like phonenumber,name from phonebook.
And check the answer posted by jon
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;
}
AND 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;
}
}
hope this helps you.
Related
I'm trying to import contacts into my app, but struggling with getting the company name. Here's my code:
public List<ContactItem> getContactList(){
ArrayList<ContactItem> contactList = new ArrayList<ContactItem>();
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()) {
ContactItem aContact = new ContactItem();
int idFieldColumnIndex = 0;
int nameFieldColumnIndex = 0;
int numberFieldColumnIndex = 0;
int companyFieldColumnIndex = 0;
String contactId = contacts.getString(contacts.getColumnIndex(ContactsContract.Contacts._ID));
nameFieldColumnIndex = contacts.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME);
if (nameFieldColumnIndex > -1)
{
aContact.setName(contacts.getString(nameFieldColumnIndex));
}
// Tried to get a company, but
// this always returns -1
companyFieldColumnIndex = contacts.getColumnIndex(ContactsContract.CommonDataKinds.Organization.COMPANY);
if (companyFieldColumnIndex > -1)
{
Log.d(TAG, "getContactList: starts");
aContact.setCompany(contacts.getString(companyFieldColumnIndex));
}
PROJECTION = new String[] {ContactsContract.CommonDataKinds.Phone.NUMBER};
final Cursor phone = managedQuery(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, PROJECTION, ContactsContract.Data.CONTACT_ID + "=?", new String[]{String.valueOf(contactId)}, null);
if(phone.moveToFirst()) {
while(!phone.isAfterLast())
{
numberFieldColumnIndex = phone.getColumnIndex(ContactsContract.CommonDataKinds.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;
}
I add a comment in my code, where i'm trying to get the contact's company name, but i always get -1. Some contacts have the company name, so something wrong in this part of code. How to get the company properly?
First thing, you are passing Projection which doesn't contains anything related to Company name so of course you won't get it.
Other thing which I am not sure is, you need to pass contact's RawId instead of ID to fetch the Company name. Here's something how you should do it,
String contactId = contacts.getString(contacts.getColumnIndex(ContactsContract.Contacts._ID));
String rawContactId = getRawContactId(contactId);
String companyName = getCompanyName(rawContactId);
& here are the functions you'll need:
private String getRawContactId(String contactId) {
String[] projection = new String[]{ContactsContract.RawContacts._ID};
String selection = ContactsContract.RawContacts.CONTACT_ID + "=?";
String[] selectionArgs = new String[]{contactId};
Cursor c = mContentResolver.query(ContactsContract.RawContacts.CONTENT_URI, projection, selection, selectionArgs, null);
if (c == null) return null;
int rawContactId = -1;
if (c.moveToFirst()) {
rawContactId = c.getInt(c.getColumnIndex(ContactsContract.RawContacts._ID));
}
c.close();
return String.valueOf(rawContactId);
}
and:
private String getCompanyName(String rawContactId) {
try {
String orgWhere = ContactsContract.Data.RAW_CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?";
String[] orgWhereParams = new String[]{rawContactId,
ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE};
Cursor cursor = mContentResolver.query(ContactsContract.Data.CONTENT_URI,
null, orgWhere, orgWhereParams, null);
if (cursor == null) return null;
String name = null;
if (cursor.moveToFirst()) {
name = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Organization.COMPANY));
}
cursor.close();
return name;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
I am not able to find any appropriate solution for below issue. I have some method which return contact names and phone numbers from phone, and it works on lots of devices.
But, problem is this method does not work on my htc(android 4.3.1). I think, maybe main cause is on line of declaration of cursor(Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);), because I checked Cursor object by getCount method and it showed me a zero, which means it could not get any data. I tried many ways of declaring Cursor object, but I didn't succeed.
thanks in advance! Please check Code mentioned below:
private List<String> getContactNames() {
List<String> contacts = new ArrayList<>();
// Get the ContentResolver
ContentResolver cr = getContentResolver();
// Get the Cursor of all the contacts
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));
phoneNumber = phoneNumber.replaceAll("[()+]", "");
phoneNumber = phoneNumber.replaceAll(" ", "");
if (phoneNumber.startsWith("8")) {
phoneNumber = phoneNumber.replaceFirst("8", "7");
}
//contactNames.add(phoneNumber);
contacts.add(name + "&&" + phoneNumber);
}
phones.close();
Collections.sort(contacts, String.CASE_INSENSITIVE_ORDER);
List<String> contactList =
new ArrayList<>(new LinkedHashSet<String>(contacts));
for (int i = 0; i < contactList.size(); i++) {
String tem = contactList.get(i);
String[] arr = tem.split("&&");
contactNumbers.add(arr[1]);
contactNames.add(arr[0]);
}
//Toast.makeText(this, contactNames.toString(), Toast.LENGTH_LONG).show();
return contactList;
}
Use this.
public class ContactsProvider {
private Uri QUERY_URI = ContactsContract.Contacts.CONTENT_URI;
private String CONTACT_ID = ContactsContract.Contacts._ID;
private String DISPLAY_NAME = ContactsContract.Contacts.DISPLAY_NAME;
private Uri EMAIL_CONTENT_URI = ContactsContract.CommonDataKinds.Email.CONTENT_URI;
private String EMAIL_CONTACT_ID = ContactsContract.CommonDataKinds.Email.CONTACT_ID;
private String EMAIL_DATA = ContactsContract.CommonDataKinds.Email.DATA;
private String HAS_PHONE_NUMBER = ContactsContract.Contacts.HAS_PHONE_NUMBER;
private String PHONE_NUMBER = ContactsContract.CommonDataKinds.Phone.NUMBER;
private Uri PHONE_CONTENT_URI = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
private String PHONE_CONTACT_ID = ContactsContract.CommonDataKinds.Phone.CONTACT_ID;
private String STARRED_CONTACT = ContactsContract.Contacts.STARRED;
private ContentResolver contentResolver;
public ContactsProvider() {
contentResolver = GenericApplication.getContext().getContentResolver();
}
public List<Contact> getContacts() {
List<Contact> contactList = new ArrayList<Contact>();
String[] projection = new String[]{CONTACT_ID, DISPLAY_NAME, HAS_PHONE_NUMBER, STARRED_CONTACT};
String selection = null;
Cursor cursor = contentResolver.query(QUERY_URI, projection, selection, null, null);
while (cursor.moveToNext()) {
Contact contact = getContact(cursor);
contactList.add(contact);
}
cursor.close();
return contactList;
}
private Contact getContact(Cursor cursor) {
String contactId = cursor.getString(cursor.getColumnIndex(CONTACT_ID));
String name = (cursor.getString(cursor.getColumnIndex(DISPLAY_NAME)));
Uri uri = Uri.withAppendedPath(QUERY_URI, String.valueOf(contactId));
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(uri);
String intentUriString = intent.toUri(0);
Contact contact = new Contact();
contact.id = Integer.valueOf(contactId);
contact.name = name;
contact.uriString = intentUriString;
getPhone(cursor, contactId, contact);
getEmail(contactId, contact);
return contact;
}
private void getEmail(String contactId, Contact contact) {
Cursor emailCursor = contentResolver.query(EMAIL_CONTENT_URI, null, EMAIL_CONTACT_ID + " = ?", new String[]{contactId}, null);
while (emailCursor.moveToNext()) {
String email = emailCursor.getString(emailCursor.getColumnIndex(EMAIL_DATA));
if (!TextUtils.isEmpty(email)) {
contact.email = email;
}
}
emailCursor.close();
}
private void getPhone(Cursor cursor, String contactId, Contact contact) {
int hasPhoneNumber = Integer.parseInt(cursor.getString(cursor.getColumnIndex(HAS_PHONE_NUMBER)));
if (hasPhoneNumber > 0) {
Cursor phoneCursor = contentResolver.query(PHONE_CONTENT_URI, null, PHONE_CONTACT_ID + " = ?", new String[]{contactId}, null);
while (phoneCursor.moveToNext()) {
String phoneNumber = phoneCursor.getString(phoneCursor.getColumnIndex(PHONE_NUMBER));
contact.phone = phoneNumber;
}
phoneCursor.close();
}
}
}
Use this method:
private void LoadContactsWithPhone() {
TextView contactView = (TextView) getView().findViewById(R.id.txtContacts);
contactView.setText("");
Cursor cursor = getContactsWithPhone();
while (cursor.moveToNext()) {
String displayName = cursor.getString(cursor
.getColumnIndex(ContactsContract.Data.DISPLAY_NAME));
String phoneNo = cursor.getString(cursor
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
contactView.append("Name: ");
contactView.append(displayName);
contactView.append("\n");
contactView.append("Phone: ");
contactView.append(phoneNo);
contactView.append("\n\n");
}
}
private Cursor getContactsWithPhone() {
Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
String[] projection = new String[]{ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.NUMBER
};
String selection = ContactsContract.Contacts.HAS_PHONE_NUMBER + " = ?";
String[] selectionArgs = new String[]{String.valueOf(1)};
String sortOrder = ContactsContract.Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC";
return getActivity().getContentResolver().query(uri, projection, selection, selectionArgs, sortOrder);
}
Sorry guys, main cause was the device itself, I checked other similar applications that use the device contacts as whatsapp, and these applications are also unable to use the phone's contacts. All answers are presented here work perfectly , as good as my method.
Please used the following code its working on my end on all devices:-
public ArrayList<Contact_Model> getContacts(){
ArrayList<Contact_Model> contact_models = new ArrayList<>();
// ContentResolver cr = context.getActivity().getContentResolver();
ContentProviderClient mCProviderClient = context.getActivity().getContentResolver().acquireContentProviderClient(ContactsContract.Contacts.CONTENT_URI);
Cursor cur = mCProviderClient.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
if (cur.getCount() > 0) {
while (cur.moveToNext()) {
Contact_Model contact_model = new Contact_Model();
String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
String firstname;
String lastName = "";
if (name != null) {
contact_model.setContactId(id);
contact_model.setContactName(name);
if (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
// get the phone number
Cursor pCur = mCProviderClient.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));
contact_model.setContactNumber(phone);
}
pCur.close();
// get email and type
Cursor emailCur = mCProviderClient.query(
ContactsContract.CommonDataKinds.Email.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?",
new String[]{id}, null);
while (emailCur.moveToNext()) {
// This would allow you get several email addresses
// if the email addresses were stored in an array
String email = emailCur.getString(
emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
contact_model.setContactEmail(email);
}
emailCur.close();
Cursor photoCursor = mCProviderClient.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
new String[]{id}, null);
while (photoCursor.moveToNext()) {
String photo = photoCursor.getString(photoCursor.getColumnIndex(ContactsContract.Contacts.PHOTO_ID));
if (photo == null) {
contact_model.setContactPhoto("");
} else {
contact_model.setContactPhoto(photo);
}
}
contact_model.setContactOtherDetails("");
photoCursor.close();
// Get note.......
String noteWhere = ContactsContract.Data.CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?";
String[] noteWhereParams = new String[]{id,
ContactsContract.CommonDataKinds.Note.CONTENT_ITEM_TYPE};
Cursor noteCur = mCProviderClient.query(ContactsContract.Data.CONTENT_URI, null, noteWhere, noteWhereParams, null);
if (noteCur.moveToFirst()) {
String note = noteCur.getString(noteCur.getColumnIndex(ContactsContract.CommonDataKinds.Note.NOTE));
System.out.println("Note " + note);
contact_model.setNote(note);
}
noteCur.close();
// Get Organizations.........
String orgWhere = ContactsContract.Data.CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?";
String[] orgWhereParams = new String[]{id,
ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE};
Cursor orgCur = mCProviderClient.query(ContactsContract.Data.CONTENT_URI,
null, orgWhere, orgWhereParams, null);
if (orgCur.moveToFirst()) {
String orgName = orgCur.getString(orgCur.getColumnIndex(ContactsContract.CommonDataKinds.Organization.DATA));
String title = orgCur.getString(orgCur.getColumnIndex(ContactsContract.CommonDataKinds.Organization.TITLE));
if (orgName != null) {
contact_model.setOrganization(orgName);
}
if (title != null) {
contact_model.setJob(title);
}
}
orgCur.close();
}
contact_models.add(contact_model);
}
}
}
return contact_models;
}
Contact Model:-
public class Contact_Model implements Serializable {
private String contactId = "", contactName = "", contactNumber = "", contactEmail = "", contactPhoto = "", contactOtherDetails = "";
private String firstName = "", lastName = "", note = "", organization = "", job = "", dob = "";
ContactAccount contactAccount;
public Contact_Model() {
}
public Contact_Model(String contactId, String contactName, String contactNumber, String contactEmail, String contactPhoto, String contactOtherDetails, String firstName, String lastName,
String note, String organization, String job, String dob) {
this.contactId = contactId;
this.contactName = contactName;
this.contactNumber = contactNumber;
this.contactEmail = contactEmail;
this.contactPhoto = contactPhoto;
this.contactOtherDetails = contactOtherDetails;
this.firstName = firstName;
this.lastName = lastName;
this.note = note;
this.organization = organization;
this.dob = dob;
this.job = job;
}
public ContactAccount getContactAccount() {
return contactAccount;
}
public void setContactAccount(ContactAccount contactAccount) {
this.contactAccount = contactAccount;
}
public String getDob() {
return dob;
}
public void setDob(String dob) {
this.dob = dob;
}
public String getNote() {
return note;
}
public void setNote(String note) {
this.note = note;
}
public String getOrganization() {
return organization;
}
public void setOrganization(String organization) {
this.organization = organization;
}
public String getJob() {
return job;
}
public void setJob(String job) {
this.job = job;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getContactId() {
return contactId;
}
public void setContactId(String contactId) {
this.contactId = contactId;
}
public String getContactName() {
return contactName;
}
public void setContactName(String contactName) {
this.contactName = contactName;
}
public String getContactNumber() {
return contactNumber;
}
public void setContactNumber(String contactNumber) {
this.contactNumber = contactNumber;
}
public String getContactEmail() {
return contactEmail;
}
public void setContactEmail(String contactEmail) {
this.contactEmail = contactEmail;
}
public String getContactPhoto() {
return contactPhoto;
}
public void setContactPhoto(String contactPhoto) {
this.contactPhoto = contactPhoto;
}
public String getContactOtherDetails() {
return contactOtherDetails;
}
public void setContactOtherDetails(String contactOtherDetails) {
this.contactOtherDetails = contactOtherDetails;
}
}
ContactAccount.class
public class ContactAccount implements Serializable {
String accountName = "", accountType = "";
public ContactAccount(){
}
public ContactAccount(String accountName, String accountType) {
this.accountName = accountName;
this.accountType = accountType;
}
public String getAccountName() {
return accountName;
}
public void setAccountName(String accountName) {
this.accountName = accountName;
}
public String getAccountType() {
return accountType;
}
public void setAccountType(String accountType) {
this.accountType = accountType;
}
}
Hope this helps you..
I'm creating an app which require Contacts with their phone numbers. I'm able to get the Contact name list using following code
private Contact[] contact_read;
private Cursor mCursor;
String[] projection = new String[] { Contacts.HAS_PHONE_NUMBER,
Contacts._ID, Contacts.DISPLAY_NAME };
mCursor = managedQuery(Contacts.CONTENT_URI, projection,
Contacts.HAS_PHONE_NUMBER + "=?", new String[] { "1" },
Contacts.DISPLAY_NAME);
if (mCursor != null) {
mCursor.moveToFirst();
contact_read = new Contact[mCursor.getCount()];
int j = 0;
do {
contact_read[j] = new Contact(mCursor.getString(mCursor
.getColumnIndex(Contacts.DISPLAY_NAME)));
j++;
} while (mCursor.moveToNext());
} else {
System.out.println("Cursor is NULL");
}
The Contact class is
private static class Contact {
private String name = "";
public Contact() {
}
public Contact(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
But when I add the following code to get phone number, the app crashes
ContentResolver cr = getContentResolver();
String id = mCursor.getString(mCursor.getColumnIndex(Contacts._ID));
Cursor pCur = cr.query(Phone.CONTENT_URI,null,Phone.CONTACT_ID +" = ?", new String[]{id}, null);
pCur.moveToFirst();
int j = 0;
do {
contact_read[j] = new Contact(pCur.getString(pCur.getColumnIndex(Phone.NUMBER)));
j++;
} while (pCur.moveToNext());
Any suggestions from your side what changes need to be done to get the phone numbers??
This is the code for getting all the contacts from our phone
while (phones.moveToNext())
{
String name=phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
arraylist_connect.add(new Connect(name,phoneNumber,"Mobile"));
}
phones.close();
I need some help, because I can't find any solutions on Google :-(
Is there a easy way to get the names of the phone books on my device. I want fill a spinner with these values. So I need a result which contains entries like: SIM, Google, Local, etc.
These values are accessible by the Contacts Provider (I think in ContactsContract.RawContacts) and named as ACCOUNT_TYPE and ACCOUNT_NAME. But I think it couldn't be the solution to get the values with a cursor from the Contacts Provider.
Thank you so much for any suggestions.
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;
}
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;
}
}
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.