I'm create an application to get all contacts from phone book of Android device. I synch my contacts list from Gmail to android device and I see all contacts in phone book. But when running application, cannot get any contacts from phone book.
Here is my code
MainActivity.java
public class MainActivity extends Activity {
private TextView outputText;
TextView txtViewContactsInfor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
outputText =(TextView)findViewById(R.id.textView2);
txtViewContactsInfor = (TextView) findViewById(R.id.txtViewContactsInfor);
Import_contacts_from_address_book();
}
private void Import_contacts_from_address_book() {
// TODO Auto-generated method stub
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 PHONECONTACT_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 EMAIL = ContactsContract.CommonDataKinds.Email.DATA;
StringBuffer output = new StringBuffer();
ContentResolver contentResolver = getContentResolver();
Cursor cursor = contentResolver.query(CONTENT_URI, null, null, null, null);
System.out.println("---------------------->"+cursor.getCount());
if(cursor.getCount() >0){
int aa = cursor.getCount();
while(cursor.moveToNext()){
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("\nFirst Name: "+name);
// Query and loop for every phone number of the contact
Cursor phoneCursor = contentResolver.query(PHONECONTENT_URI, null, PHONECONTACT_ID + "=?", new String[]{contact_id}, null);
while(phoneCursor.moveToNext()){
phoneNumber = phoneCursor.getString(phoneCursor.getColumnIndex(NUMBER));
output.append("\n Phone number: "+phoneNumber);
}
phoneCursor.close();
// Query and loop for every email of the contact
Cursor emailCurosr = contentResolver.query(EMAILCONTENT_URI, null, EMAILCONTACT_ID+"=?",new String[]{contact_id},null);
while(emailCurosr.moveToNext()){
email = emailCurosr.getString(emailCurosr.getColumnIndex(EMAIL));
output.append("\nEmail: "+email);
}
emailCurosr.close();
}
output.append("\n");
}
cursor.close();
}
outputText.setText(output.toString());
}
I debug in cursor.getCount and see "544 contact" was found. But
int hasPhoneNumber = Integer.parseInt(cursor.getString(cursor.getColumnIndex(HAS_PHONE_NUMBER))); always zero.
I dont know why.
You might have a lot contacts without number, because contacts are stored in multiple columns.
I simplified and modified your code to count rows with and with out numbers and let it run on my phone:
private void readContacts() {
Cursor c = getContentResolver()
.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
int foundWithNumber = 0;
int foundWithOutNumber = 0;
if (c.moveToFirst()) {
int idHasNumber = c.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER);
do {
boolean hasNumber = c.getInt(idHasNumber) > 0;
if (hasNumber) {
++foundWithNumber;
} else {
++foundWithOutNumber;
}
} while (c.moveToNext());
}
Log.d(TAG, "foundWithNumber: " + foundWithNumber);
Log.d(TAG, "foundWithOutNumber: " + foundWithOutNumber);
c.close();
}
The ouput on my phone is:
MainActivity D foundWithNumber: 184
D foundWithOutNumber: 303
So, I guess, you just looked at the wrong rows. ;)
You nead add Read contact permission in Android manifest
android.permission.READ_CONTACTS
Related
I am able to retrieve the contact ID, but then later I wish to separately retrieve the phone number based on the contact ID. The code below is returning a null result for the phone number. (I do wish later to retrieve the name and phone number together and populate a view, but I am just trying to get the phone number to work first).
In my onCreate I have this code
String phoneNum = getPhoneNumber(myID);
TextView phoneTextView = (TextView) findViewById(R.id.textViewPhone);
phoneTextView.setText(phoneNum);
This is the method for getPhoneNumber()
protected String getPhoneNumber(String id) {
ArrayList<String> phones = new ArrayList<String>();
Cursor cursor = getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
new String[]{id}, null);
while (cursor.moveToNext()) {
phones.add(cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)));
}
cursor.close();
String phoneNum;
phoneNum = phones.get(0);
return phoneNum;
}//end getPhoneNumber();
}
This produces the error java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0, which I plan on creating some error handling for. But still, I am certain I have the ID from the previous code, so I don't know why the ArrayList returns null. If you would like to see that code, it is also in my onCreate:
Cursor cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
if (cursor.getCount() != 0) {
int numContacts = cursor.getCount();
ArrayList<String> idList = new ArrayList<>();
Random rand = new Random();
int randomNum = rand.nextInt(numContacts);
while (cursor.moveToNext()) {
String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
idList.add(id);
}
myID = idList.get(randomNum);
String myString = Integer.toString(randomNum);
TextView myTextView = (TextView) findViewById(R.id.textViewID);
myTextView.setText(myString);
if (myID != null) {
myTextView.setText(myID);
} else {
myTextView.setText("Try Again!");
}
} else {
Toast.makeText(getApplicationContext(), "Your have no contacts.", Toast.LENGTH_SHORT).show();
}
cursor.close();
// You can fetch the Contact Number and Email With Following Methods.
String phone = getPhoneNumber(ContactId);
String email = getEmail("" + ContactId);
private String getPhoneNumber(long id) {
String phone = null;
Cursor phonesCursor = null;
phonesCursor = queryPhoneNumbers(id);
if (phonesCursor == null || phonesCursor.getCount() == 0) {
// No valid number
//signalError();
return null;
} else if (phonesCursor.getCount() == 1) {
// only one number, call it.
phone = phonesCursor.getString(phonesCursor
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
} else {
phonesCursor.moveToPosition(-1);
while (phonesCursor.moveToNext()) {
// Found super primary, call it.
phone = phonesCursor.getString(phonesCursor
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
break;
}
}
return phone;
}
private Cursor queryPhoneNumbers(long contactId) {
ContentResolver cr = getContentResolver();
Uri baseUri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI,
contactId);
Uri dataUri = Uri.withAppendedPath(baseUri,
ContactsContract.Contacts.Data.CONTENT_DIRECTORY);
Cursor c = cr.query(dataUri, new String[]{ContactsContract.CommonDataKinds.Phone._ID, ContactsContract.CommonDataKinds.Phone.NUMBER,
ContactsContract.CommonDataKinds.Phone.IS_SUPER_PRIMARY, ContactsContract.RawContacts.ACCOUNT_TYPE,
ContactsContract.CommonDataKinds.Phone.TYPE,
ContactsContract.CommonDataKinds.Phone.LABEL},
ContactsContract.Data.MIMETYPE + "=?",
new String[]{ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE}, null);
if (c != null && c.moveToFirst()) {
return c;
}
return null;
}
private String getEmail(String id) {
String email = "";
ContentResolver cr = getContentResolver();
Cursor emailCur = cr.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
email = emailCur.getString(
emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
// String emailType = emailCur.getString(
// emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.TYPE));
}
emailCur.close();
return email;
}
I have not been able to successfully retrieve code based on the Contact ID - but this post gave me a clue: Retrieving a phone number with ContactsContract in Android - function doesn't work
I have altered my original code to query on DISPLAY_NAME instead and things are working now. Here is the method I am using to retrieve the phone number:
private String retrieveContactNumber(String contactName) {
Log.d(TAG, "Contact Name: " + contactName);
Cursor cursorPhone = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
new String[]{ContactsContract.CommonDataKinds.Phone.NUMBER},
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " = ? AND " +
ContactsContract.CommonDataKinds.Phone.TYPE + " = " +
ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE,
new String[]{contactName},
null);
if (cursorPhone.moveToFirst()) {
contactNumber = cursorPhone.getString(cursorPhone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
}
cursorPhone.close();
Log.d(TAG, "Contact Phone Number: " + contactNumber);
return contactNumber;
}
I am using the code below to get a contact name and ID but I am not getting the phone number. How can I get the phone number from the code below?
ContentResolver contentResolver = getBaseContext().getContentResolver();
Uri uri = ContactsContract.Contacts.CONTENT_URI;
String[] projection = {
ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.Contacts.HAS_PHONE_NUMBER,
ContactsContract.Contacts.STARRED,
ContactsContract.Contacts.TIMES_CONTACTED,
ContactsContract.Contacts.LAST_TIME_CONTACTED
};
String selection = String.format("%s > 0", ContactsContract.Contacts.HAS_PHONE_NUMBER);
String[] selectionArgs = null;
String sortOrder = String.format(
"%s DESC, %s DESC, %S DESC, UPPER(%s) ASC",
ContactsContract.Contacts.STARRED,
ContactsContract.Contacts.TIMES_CONTACTED,
ContactsContract.Contacts.LAST_TIME_CONTACTED,
ContactsContract.Contacts.DISPLAY_NAME
);
Cursor cursor = contentResolver.query(uri, projection, selection, selectionArgs, sortOrder);
if (cursor.getCount() > 0) {
while (cursor.moveToNext()) {
String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
if (Integer.parseInt(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
System.out.println("name : " + name + ", ID : ");
}
}
}
cursor.close();
}
CModel.java
public class CModel {
String firstname;
String lastname;
String contactno;
String Imagepath;
int ID;
String contactid;
public String getCheck() {
return Check;
}
String Check;
public String getContactid() {
return contactid;
}
public CModel(String fnm, String lastname, String userprofile, int ID, String contactno, String Check) {
this.firstname = fnm;
this.lastname = lastname;
this.Imagepath = userprofile;
this.ID = ID;
this.contactno = contactno;
this.Check = Check;
}
public String getFirstname() {
return firstname;
}
public String getLastname() {
return lastname;
}
public String getContactno() {
return contactno;
}
public String getImagepath() {
return Imagepath;
}
public int getID() {
return ID;
}
in your activity file call this method
private ArrayList<CModel> getcontact() {
ArrayList<CModel> contactlist = new ArrayList<CModel>;
try {
Bitmap my_btmp = null;
String profilepic;
String phone = null;
contactlist = new ArrayList<CModel>();
ContentResolver cr = getContentResolver();
String[] projection = new String[]{ContactsContract.Contacts._ID, ContactsContract.Contacts.DISPLAY_NAME};
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, projection, null, null,
ContactsContract.Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC");
while (cur.moveToNext()) {
String contactId = cur.getString(cur.getColumnIndex(ContactsContract.Data._ID));
String displayName = cur.getString(cur.getColumnIndex(ContactsContract.Data.DISPLAY_NAME));
Uri my_contact_Uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_URI, String.valueOf(contactId));
InputStream photo_stream = ContactsContract.Contacts.openContactPhotoInputStream(getContentResolver(), my_contact_Uri);
Cursor pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
new String[]{contactId}, null);
while (pCur.moveToNext()) {
phone = pCur.getString(
pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
}
pCur.close();
if (photo_stream != null) {
BufferedInputStream buf = new BufferedInputStream(photo_stream);
my_btmp = BitmapFactory.decodeStream(buf);
profilepic = BitMapToString(my_btmp);
} else {
Bitmap bitmap = BitmapFactory.decodeResource(HomePage.this.getResources(), R.drawable.profilepic);
my_btmp = bitmap;
profilepic = BitMapToString(my_btmp);
}
String columns[] = {
ContactsContract.CommonDataKinds.Event.START_DATE,
ContactsContract.CommonDataKinds.Event.TYPE,
ContactsContract.CommonDataKinds.Event.MIMETYPE,
};
String where =ContactsContract.CommonDataKinds.Event.MIMETYPE + " = '" + ContactsContract.CommonDataKinds.Event.CONTENT_ITEM_TYPE + "' and " + ContactsContract.Data.CONTACT_ID + " = " + contactId;
String[] selectionArgs = null;
String sortOrder = ContactsContract.Contacts.DISPLAY_NAME;
Cursor birthdayCur = cr.query(ContactsContract.Data.CONTENT_URI, columns, where, selectionArgs, sortOrder);
if (birthdayCur.getCount() > 0) {
if (birthdayCur.moveToFirst()) {
do {
contactlist.add(new CModel(displayName, "", profilepic, 0, phone,"phone"));
boolean flag = con.comparedata(phone);
} while (birthdayCur.moveToNext());
}
}
birthdayCur.close();
}
cur.close();
} catch (Exception e) {
}
return contactlist;
}
There is no phone Number in 'ContactsContract.Contacts' but 'ContactsContract.Contacts._ID' and 'ContactsContract.CommonDataKinds.Phone.CONTACT_ID' are same for each contact. Hence you can get phone number from 'ContactsContract.CommonDataKinds.Phone.CONTENT_URI' . Put this code inside your cursor's loop. Overall these are two queries but at least you know where to search. This should not take much time in execution.
Cursor phoneCursor = managedQuery(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + contactId , null, null);
while (phoneCursor.moveToNext()) {
String phone = phoneCursor.getString(phoneCursor
.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.NUMBER));
}
EDIT: This is my attempt at retrieving every phone number in 1 query but I'm unsure of the behavior if any contacts without phone numbers exist; in general it is best practice to always query the list of contacts that have phone numbers, and then query only those contacts numbers.
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));
//Do something with each name and phone somewhere each time you loop through; in your provided code you seemed to be printing them out
}
phones.close();
For reference: Read all contact's phone numbers in android
This older post seemed helpful, based on some previous work I've done with writing to contacts: How to get contacts' phone number in Android
In general, the phone number is stored as a:
ContactsContract.CommonDataKinds.Phone.NUMBER
So taking a snippet of the code you provided, I would edit roughly as so:
if (cursor.getCount() > 0) {
while (cursor.moveToNext()) {
String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
String number = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
...
...
cursor.close();
}
Of course you'll need to make sure in your query that you're grabbing the right segment of data from the contact (i.e. updating your projection), but that should hopefully point you in the right direction!
I'm making a Dialer and I want to search the contacts by name.
But since the Dialer accepts only numbers, how should I search for JOHN by entering the number 5-6-4-6? Are there any existing methods to do so in android?
If this number 5-6-4-6 exists in your contacst than you can use Content uri and hpone uri to lookup for this number and you can compare it with the fetched results...
You can fetch all the contacts and you get the name by comparing this number an d with the fetched numbers from the andorid conatcts api.
public void fetchContacts() {
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 = new StringBuffer();
ContentResolver contentResolver = getContentResolver();
Cursor cursor = contentResolver.query(CONTENT_URI, null,null, null, null);
// Loop for every contact in the phone
if (cursor.getCount() > 0) {
while (cursor.moveToNext()) {
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);
// Query and loop for every phone number of the 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();
// Query and loop for every email of 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("\nEmail:" + email);
}
emailCursor.close();
}
output.append("\n");
}
outputText.setText(output);
}
}
}
this link may help you..
there are various ways to do this.
Assign each letter a numeric code as per numeric keypad with letters.
e.g.
assign 2 to a b & c
assign 3 to d e & f and so on.
Then modify your search accordingly.
I create an application to get all contact in addressbook (phone book) of Android device like Viper application.
Here is my code:
private void Import_contacts_from_address_book() {
// TODO Auto-generated method stub
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 PHONECONTACT_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 EMAIL = ContactsContract.CommonDataKinds.Email.DATA;
StringBuffer output = new StringBuffer();
ContentResolver contentResolver = getContentResolver();
Cursor cursor = contentResolver.query(CONTENT_URI, null, null, null, null);
System.out.println("---------------------->"+cursor.getCount());
if(cursor.getCount() >0){
countContact = cursor.getCount();
while(cursor.moveToNext()){
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)));
//------------------- Catch phone number, neu phone >0 thi get phone, ko thi lam chuyen khac
//if(hasPhoneNumber > 0 ){
output.append("\nFirst Name: "+name);
// Query and loop for every phone number of the contact
Cursor phoneCursor = contentResolver.query(PHONECONTENT_URI, null, PHONECONTACT_ID + "=?", new String[]{contact_id}, null);
while(phoneCursor.moveToNext()){
phoneNumber = phoneCursor.getString(phoneCursor.getColumnIndex(NUMBER));
output.append("\n Phone number: "+phoneNumber);
}
phoneCursor.close();
// Query and loop for every email of the contact
Cursor emailCurosr = contentResolver.query(EMAILCONTENT_URI, null, EMAILCONTACT_ID+"=?",new String[]{contact_id},null);
while(emailCurosr.moveToNext()){
email = emailCurosr.getString(emailCurosr.getColumnIndex(EMAIL));
output.append("\nEmail: "+email);
}
emailCurosr.close();
//}
output.append("\n");
}
cursor.close();
}
txtViewContactsInfor.setText("Contacts: "+String.valueOf(countContact));
outputText.setText(output.toString());
}
I try to import 1000 contact and it take at least 45 second.
Is there any way to improve speed?
And when I change some information in contact of addressbook (phone book) in Android device. I using onResume() to update new information for my application but It's reload all page so It take a long time. But I see on Viper, the data updating immediately. So, is there any I can update or sync data from my device to my application like Viper application or improve speed updating, reload page ?
Any help would be much appreciated! Thanks!
Query operation is very long operation on android, because each time, when you call query, system opens database file. Opening file is expensive in android. You should call query as rarely as possible. This is my solution:
public class Contact {
public String name;
public List<String> phones;
public List<String> emails;
}
private static final Uri CONTENT_URI = ContactsContract.Contacts.CONTENT_URI;
private static final String _ID = ContactsContract.Contacts._ID;
private static final String DISPLAY_NAME = ContactsContract.Contacts.DISPLAY_NAME;
private static final Uri PHONE_CONTENT_URI = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
private static final String PHONE_CONTACT_ID = ContactsContract.CommonDataKinds.Phone.CONTACT_ID;
private static final String NUMBER = ContactsContract.CommonDataKinds.Phone.NUMBER;
private static final Uri EMAIL_CONTENT_URI = ContactsContract.CommonDataKinds.Email.CONTENT_URI;
private static final String EMAIL_CONTACT_ID = ContactsContract.CommonDataKinds.Email.CONTACT_ID;
private static final String EMAIL = ContactsContract.CommonDataKinds.Email.DATA;
private Collection<Contact> importContactsFromAddressBook() {
Map<String, Contact> contactMap = new HashMap<String, Contact>();
ContentResolver contentResolver = getContentResolver();
Cursor cursor = contentResolver.query(CONTENT_URI, null, null, null, null);
if (cursor.getCount() > 0) {
while (cursor.moveToNext()) {
String contactId = cursor.getString(cursor.getColumnIndex(_ID));
String name = cursor.getString(cursor.getColumnIndex(DISPLAY_NAME));
Contact contact = new Contact();
contact.name = name;
contact.phones = new ArrayList<String>();
contact.emails = new ArrayList<String>();
contactMap.put(contactId, contact);
}
}
cursor.close();
// Query and loop for every phone number of the contact
Cursor phoneCursor = contentResolver.query(PHONE_CONTENT_URI, null, null, null, null);
while (phoneCursor.moveToNext()) {
String contactId = phoneCursor.getString(phoneCursor.getColumnIndex(PHONE_CONTACT_ID));
String phoneNumber = phoneCursor.getString(phoneCursor.getColumnIndex(NUMBER));
Contact contact = contactMap.get(contactId);
contact.phones.add(phoneNumber);
}
phoneCursor.close();
// Query and loop for every email of the contact
Cursor emailCursor = contentResolver.query(EMAIL_CONTENT_URI, null, EMAIL_CONTACT_ID + "=?", new String[]{contactId}, null);
while (emailCursor.moveToNext()) {
String contactId = emailCursor.getString(emailCursor.getColumnIndex(EMAIL_CONTACT_ID));
String email = emailCursor.getString(emailCursor.getColumnIndex(EMAIL));
Contact contact = contactMap.get(contactId);
contact.emails.add(email);
}
emailCursor.close();
return contactMap.values();
}
I'm trying to read contact numbers from users contact list. Here is my code
Cursor cursor = getContacts();
if(cursor.getCount()>0){
while (cursor.moveToNext()) {
String displayName = cursor.getString(cursor.getColumnIndex(ContactsContract.Data.DISPLAY_NAME));
int numberField = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
textViewDisplay.append("Name: ");
textViewDisplay.append(displayName+"Number :"+numberField);
textViewDisplay.append("\n");
}
}
You are taking cursor.getColumnIndex(COLUMN) into int. So the method as it says returns the index of COLUMN sent to it as parameter. You need Phone Number which will never be contained by an int as its size is always be greater than 4 bytes, and also it contains some special characters like +
So you need to take your Number to some String variable
Use String numberField = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
as suggested by Anuj.
use this
String numberField = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
instead of
int numberField = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
It returns "1" means that contact has phone number. try this,
String hasPhone = c.getString(c.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
String cNumber="";
if (hasPhone.equalsIgnoreCase("1"))
{
Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = "+ id,null, null);
phones.moveToFirst();
cNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
phones.close();
}
try this one :
public void readContacts() {
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null,null, null, null);
if (cur.getCount() > 0) {
while (cur.moveToNext()) {
if (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
// Get contact id (id)
String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
// Get contact name (displayName)
String displayName = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
// Get Phone Number....
Uri URI_PHONE = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
String SELECTION_PHONE = ContactsContract.CommonDataKinds.Phone.CONTACT_ID+ " = ?";
String[] SELECTION_ARRAY_PHONE = new String[] { id };
Cursor currPhone = cr.query(URI_PHONE, null,SELECTION_PHONE, SELECTION_ARRAY_PHONE, null);
int indexPhoneNo = currPhone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
int indexPhoneType = currPhone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE);
if (currPhone.getCount() > 0) {
while (currPhone.moveToNext()) {
String phoneNoStr = currPhone.getString(indexPhoneNo);
String phoneTypeStr = currPhone.getString(indexPhoneType);
}
}
currPhone.close();
}
}
}
cur.close();
}