I am new in android development i am trying to get contact number by the name
here my code goes
String contname = "Sachin";
Uri lkup = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_FILTER_URI, contname);
ContentResolver contentResolver = getContentResolver();
String NUMBER = ContactsContract.CommonDataKinds.Phone.NUMBER;
String Phone_CONTACT_ID = ContactsContract.CommonDataKinds.Phone.CONTACT_ID;
Cursor idCursor = getContentResolver().query(lkup, null, null, null, null);
while (idCursor.moveToNext()) {
String id = idCursor.getString(idCursor.getColumnIndex(ContactsContract.Contacts._ID));
String contact_id = idCursor.getString(idCursor.getColumnIndex( id ));
String key = idCursor.getString(idCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
String name = idCursor.getString(idCursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
String HAS_PHONE_NUMBER=idCursor.getString(idCursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
int hasPhoneNumber = Integer.parseInt(idCursor.getString(idCursor.getColumnIndex( HAS_PHONE_NUMBER )));
Uri PhoneCONTENT_URI = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
if (hasPhoneNumber > 0) {
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);
Toast.makeText(MainActivity.this,
phoneNumber, Toast.LENGTH_LONG).show();
}
}
Log.d(LOG_TAG, "search: "+id + " key: "+key + " name: "+name);
}
idCursor.close();
But when i run the program on mobile it shows the error "Unfortuatly programm has been closed"
A shorter version; you still need that permission (android.permission.READ_CONTACTS)
public String getPhoneNumber(String name, Context context) {
String ret = null;
String selection = ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME+" like'%" + name +"%'";
String[] projection = new String[] { ContactsContract.CommonDataKinds.Phone.NUMBER};
Cursor c = context.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
projection, selection, null, null);
if (c.moveToFirst()) {
ret = c.getString(0);
}
c.close();
if(ret==null)
ret = "Unsaved";
return ret;
}
Hope it will help you.
Related
I am developing a contact app having three fragments (callLog,contactList,favoriteContactList). when moving one to another fragment, it takes time to retrieve all contacts. I have approx 276 contacts on my device. Any solution to this which reduce time.
ContentResolver cr = getContext().getContentResolver();
String[] projection = {ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.Contacts.PHOTO_URI,
ContactsContract.Contacts.HAS_PHONE_NUMBER};
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, projection, null, null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC");
String id, name, image_uri, phone = "";
if (cur != null && cur.getCount() > 0) {
while (cur.moveToNext()) {
id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
image_uri = cur.getString(cur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.PHOTO_URI));
Log.d(TAG, " name " + name + " id " + id);
// phone number
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);
if (pCur != null && pCur.moveToNext()) {
phone = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
int colIndex = pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE);
int lblIndex = pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.LABEL);
int labelType = pCur.getInt(colIndex);
String phoneType;
if (labelType == ContactsContract.CommonDataKinds.Phone.TYPE_CUSTOM) {
phoneType = pCur.getString(colIndex);
} else {
phoneType = String.valueOf(ContactsContract.CommonDataKinds.Phone.getTypeLabel(this.getResources(), labelType, "Mobile"));
}
Log.d(TAG, phoneType + " " + phone);
pCur.close();
}
mContactArrayList.add(new Contact(id, name, phone, image_uri));
}
}
cur.close();
}
Try This one code
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 phone = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
String id = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID));
String image_uri = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.PHOTO_URI));
mContactArrayList.add(new Contact(id, name, phone, image_uri));
}
I think it works.
I'm trying to get contacts with their email addresses and their phone numbers.
For some reason, I only get 1 email, even though the cursor getcount returns 7790
Thank you very much for any help
public void getNameEmailDetails(){
ContentResolver contactResolver = context.getContentResolver();
Cursor cursor = contactResolver.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
Log.d("TAG", String.valueOf(cursor.getCount()));
String displayName = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
String photoUri = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.PHOTO_THUMBNAIL_URI));
String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
String lookupKey = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));
if (Integer.parseInt(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0)
{
Cursor pCur = contactResolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[] { contactId }, null);
while (pCur.moveToNext())
{
String phone = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
String type = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE));
String s = (String) ContactsContract.CommonDataKinds.Phone.getTypeLabel(context.getResources(), Integer.parseInt(type), "");
Log.d("TAG", s + " phone: " + phone);
}
pCur.close();
}
Cursor emailCursor = contactResolver.query(ContactsContract.CommonDataKinds.Email.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?", new String[] { contactId }, null);
while (emailCursor.moveToNext())
{
String phone = emailCursor.getString(emailCursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
int type = emailCursor.getInt(emailCursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.TYPE));
String s = (String) ContactsContract.CommonDataKinds.Email.getTypeLabel(context.getResources(), type, "");
Log.d("TAG", s + " email: " + phone);
}
emailCursor.close();
cursor.close();
}
}
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 want to retrieve all contact names and numbers from a mobile phone in Android. Then, I want to display that data in a ListView. How can I achieve this?
try this...
public void getContacts(ContentResolver cr) {
Cursor phones = cr.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();// close cursor
}
call method
getContacts(this.getContentResolver());
from this code you will get name n numbers save in your contact list, add them in arraylist or array, n then you may show them in listview
try {
String phoneNumber = 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;
ContentResolver contentResolver = getContentResolver();
Cursor cursor = contentResolver.query(CONTENT_URI, null, null,
null, null);
if (cursor.getCount() > 0) {
while (cursor.moveToNext()) {
String contact_id = cursor.getString(cursor
.getColumnIndex(_ID));
int hasPhoneNumber = Integer
.parseInt(cursor.getString(cursor
.getColumnIndex(HAS_PHONE_NUMBER)));
if (hasPhoneNumber > 0) {
Cursor phoneCursor = contentResolver.query(
PhoneCONTENT_URI, null, Phone_CONTACT_ID
+ " = ?", new String[] { contact_id },
null);
while (phoneCursor.moveToNext()) {
phoneNumber = phoneCursor.getString(phoneCursor
.getColumnIndex(NUMBER));
String contname = phoneCursor.getString(phoneCursor
.getColumnIndex(DISPLAY_NAME));
if (!contname.equals(null)) {
Toast.makeText(getApplicationContext(),
contname, Toast.LENGTH_SHORT).show();
}
}
}
phoneCursor.close();
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
Hello I am new on android development and I am struggling badly with coding...I have to get full contact list of my device in to dynamic growing checkbox name which can be selectable
....
It must be selected already and also which will grow dynamically
I have tried a lot of things already but dont find any answers...and I have to get the selected contacted from it on button press
public void fetchContacts() {
String phoneNumber = null;
LayoutInflater layoutInflater =
(LayoutInflater) getBaseContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View addView = layoutInflater.inflate(R.layout.contact, 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;
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 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));
// String nam[]=new String[]{name};
// Toast.makeText(getApplicationContext(), nam[0],Toast.LENGTH_LONG).show();
ch.setText(phoneNumber);
// t1.setText(name);
ch.setChecked(true);
}
phoneCursor.close();
i try this code to fetch my contact
try {
String select = "((" + Contacts.DISPLAY_NAME + " NOTNULL) AND ("
+ Contacts.HAS_PHONE_NUMBER + "=1) AND ("
+ Contacts.DISPLAY_NAME + " != '' ))";
Cursor c = cntx.getContentResolver().query(Contacts.CONTENT_URI, CONTACTS_SUMMARY_PROJECTION, select,
null, Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC");
for(int i=0;i<c.getCount();i++)
{
// contactWrap.clear();
try {
contactId = 0;
String hasPhone = "";
display_name = "";
phoneNumber = "";
c.moveToPosition(i);
contactId = c.getLong(0);
display_name = c.getString(1);
hasPhone = c.getString(7);
if (hasPhone.equalsIgnoreCase("1"))
hasPhone = "true";
else
hasPhone = "false" ;
if (Boolean.parseBoolean(hasPhone))
{
Cursor phones = cntx.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = "+ contactId,null, null);
while (phones.moveToNext())
{
int indexPhoneType = phones.getColumnIndexOrThrow(Phone.TYPE);
String phoneType = phones.getString(indexPhoneType);
phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
String lookupKey = phones.getString(phones.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));
contactWrap.add(new ContactsWrapper(contactId, display_name, phoneNumber,lookupKey,false,color_string));
}
// map.put(contactId, new ArrayList<ContactsWrapper>(contactWrap));
phones.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
ohk u can take contactID from this cursor or your code now this is my method which will give u contact photo just pass contact ID in it
public InputStream openPhoto(long contactId) {
Uri contactUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId);
Uri photoUri = Uri.withAppendedPath(contactUri, Contacts.Photo.CONTENT_DIRECTORY);
Cursor cursor = getContentResolver().query(photoUri,
new String[] {Contacts.Photo.PHOTO}, null, null, null);
if (cursor == null) {
return null;
}
try {
if (cursor.moveToFirst()) {
byte[] data = cursor.getBlob(0);
if (data != null) {
return new ByteArrayInputStream(data);
}
}
} finally {
cursor.close();
}
return null;
}
Hope this will help u Best of luck dude
you should use content provider of contact
go through this example