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();
Related
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 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.
I have a problem pulling data using an app I am buiding.
I tried to pull my app Contact List and set it in Alphabetic order A-B-C (name and PhoneNumber)
and the problem start when I tried to do the Collections.sort(name)
after I did the collocation, the name doesn't match the phone number.
How should I do the order?
Thanks!
private void GetContact() {
Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
String[] projection = new String[] {
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.NUMBER, BaseColumns._ID };
Cursor cursor =getContentResolver().query(uri, projection, null, null, null);
int id = cursor.getColumnIndex(BaseColumns._ID);
int indexName = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
int indexPhone = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
cursor.moveToFirst();
do{
String _id = cursor.getString(id);
String name = cursor.getString(indexName);
String phone = cursor.getString(indexPhone);
arrayName.add(name);
arrayPhone.add(phone);
}while (cursor.moveToNext());
Collections.sort(arrayName);
}
Use
String DISPLAY_NAME = ContactsContract.Contacts.DISPLAY_NAME;
Cursor cursor = contentResolver
.query(uri, projection, null, null, "UPPER("+ DISPLAY_NAME + ") ASC");
It will give u contacts ordered by its name with ignoring case of name.
I assume you are having problem in displaying the respective numbers of sorted contacts name. After sorting the names have different numbers??. You can do something like below, this is just an example to give you idea. Modify how you want it.
List<Empl> list = new ArrayList<Empl>();
list.add(new Empl("Harry", 123));
list.add(new Empl("Ram",3000));
list.add(new Empl("John",6000));
list.add(new Empl("Crish",2000));
list.add(new Empl("Tom",2400));
Collections.sort(list, new MyNumberComp());
System.out.println("Sorted list entries: ");
for(Empl e:list){
System.out.println(e); // Instead of printing set the list to Listview.
}
class MyNumberComp implements Comparator<Empl>{
public int compare(Empl s1, Empl s2) {
if (s1.getName().toString() == null) {
return (s2.getName().toString() == null) ? 0 : +1;
} else {
return (s2.getName().toString() == null) ? -1 : s1.getName().toString().compareTo(s2.getName().toString());
}
}
}
class Empl{
private String name;
private int number;
public Empl(String n, int s){
this.name = n;
this.number = s;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
}
try this way hope this helps you
private ArrayList<HashMap<String, String>> GetContact() {
ArrayList<HashMap<String, String>> contacts = new ArrayList<HashMap<String, String>>();
Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
String[] projection = new String[] { ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME, ContactsContract.CommonDataKinds.Phone.NUMBER, BaseColumns._ID };
Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
int id = cursor.getColumnIndex(BaseColumns._ID);
int indexName = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
int indexPhone = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
do {
HashMap<String, String> item = new HashMap<String, String>();
item.put("id", cursor.getString(id));
item.put("phone", cursor.getString(indexPhone));
item.put("name", cursor.getString(indexName));
contacts.add(item);
} while (cursor.moveToNext());
}
Collections.sort(contacts, new Comparator<HashMap<String, String>>() {
#Override
public int compare(HashMap<String, String> lhs, HashMap<String, String> rhs) {
return lhs.get("name").toLowerCase().compareTo(rhs.get("name").toLowerCase());
}
});
return contacts;
}
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.