My goal is to get the phone number and the e-mail of a contact.
I've tried to use one cursor but somehow it returns the same thing for phone and e-mail (either of the two, depending on tweaking some things). What I want right now is a hashtable that maps e-mails to phone numbers, or two hashtables, emailToID, and IDToPhone. This is what I have so far, but the IDs I use are not the same accross parameters (the a#a.com's phone is 123, their respective IDs are not the same and cannot be easily mapped). Would be grateful for help!
public String getPhoneByEmail(String userEmail){
final String EMAIL_URI = ContactsContract.CommonDataKinds.Email.DATA;
final String PHONE_URI = ContactsContract.CommonDataKinds.Phone.NUMBER;
Hashtable<String, Integer> emailToId = new Hashtable<>();
Hashtable<Integer, String> idToPhone = new Hashtable<>();
ContentResolver cr = getContext().getContentResolver();
Cursor cur1 = cr.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
null,
null, null);
Cursor cur2 = cr.query(
ContactsContract.CommonDataKinds.Email.CONTENT_URI, null,
null,
null, null);
while (cur1.moveToNext()) {
String phone = cur1.getString(cur1.getColumnIndex(PHONE_URI));
String id1 = cur1.getString(cur1.getColumnIndex(ContactsContract.CommonDataKinds.Phone._ID));
idToPhone.put(Integer.parseInt(id1), phone);
}
while (cur2.moveToNext()) {
String email = cur2.getString(cur2.getColumnIndex(EMAIL_URI));
String id2 = cur2.getString(cur2.getColumnIndex(ContactsContract.CommonDataKinds.Email._ID));
emailToId.put(email, Integer.parseInt(id2));
}
cur1.close();
cur2.close();
if (emailToId.get(userEmail)!=null){
int id = emailToId.get(userEmail);
int newId = id - 2;
String phone = idToPhone.get(newId);
return phone;
}
else return "not found";
}
Got it with help from this: https://stackoverflow.com/a/4154729/6463084
private String getPhoneByEmail(String userEmail) {
Hashtable<String, String> emailToId = new Hashtable<>();
Hashtable<String, String> idToPhone = new Hashtable<>();
ContentResolver cr = getContext().getContentResolver();
Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
while (cursor.moveToNext()) {
String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
String name = cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME));
String hasPhone = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
if (hasPhone.equalsIgnoreCase("1"))
hasPhone = "true";
else
hasPhone = "false";
if (Boolean.parseBoolean(hasPhone)) {
Cursor phones = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + contactId, null, null);
while (phones.moveToNext()) {
String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
idToPhone.put(contactId, phoneNumber);
}
phones.close();
}
Cursor emails = cr.query(ContactsContract.CommonDataKinds.Email.CONTENT_URI, null, ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = " + contactId, null, null);
while (emails.moveToNext()) {
String emailAddress = emails.getString(emails.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
emailToId.put(emailAddress, contactId);
}
emails.close();
}
cursor.close();
if (emailToId.get(userEmail) != null) {
String id = emailToId.get(userEmail);
if (idToPhone.get(id) != null) {
String phone = idToPhone.get(id);
return phone;
}
}
return "not found";
}
Try this code to Read Contact Number/Name/Email From Phone..
public void storeContactsInLocal() {
String sortOrder = ContactsContract.Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC";
// retrieve all contacts as a cursor.
Cursor cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, sortOrder);
//now we have cusror with contacts and get diffrent value from cusror.
String lastNumber = null;
while (cursor.moveToNext()) {
String name = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumber = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
String email = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
String number = phoneNumber.replaceAll("\\s+", "");
if (!number.equals(lastNumber)) {
lastNumber = number;
try {
// Save Contact in Database!
String contactDetail = "Name :" + name + " : " + "Number :" + number+ " : " + "Email :" + email;
Log.e("Contact :", contactDetail);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
Now call this Function from Your Activity like..
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Thread t = new Thread(new Runnable() {
#Override
public void run() {
storeContactsInLocal();
}
});
t.start();
}
}, 100);
Just don't forget to ask/Add Permission to 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;
}
In my code the contact fetching takes too much time to fetch the contacts and show in the application.
Please guide me where i am wrong and what should i correct in order to make execution time fast.
Here is my code.
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null,
null, null, null );
String phone = null;
List<String> phonenumber = new ArrayList<String>();
String emailContact = null;
String emailType = null;
String image_uri = "";
Bitmap bitmap = null;
if (cur.getCount() > 0) {
while (cur.moveToNext())
{
String id = cur.getString(cur
.getColumnIndex(ContactsContract.Contacts._ID));
String name = cur
.getString(cur
.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
image_uri = cur
.getString(cur
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.PHOTO_URI));
if (Integer
.parseInt(cur.getString(cur
.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0)
{
System.out.println("name : " + name + ", ID : " + id);
Cursor pCur = cr.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID
+ " = ?", new String[]{id}, null);
Log.e("pCur","dfgfdg "+pCur.getCount());
while (pCur.moveToNext())
{
phone = pCur
.getString(pCur
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
// contactid=pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
/* phonenumber.add(pCur
.getString(pCur
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)));`*/
Log.e("phone" ,phone);
}
pCur.close();
Cursor emailCur = cr.query
(
ContactsContract.CommonDataKinds.Email.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Email.CONTACT_ID
+ " = ?", new String[]{id}, null);
while (emailCur.moveToNext())
{
emailContact = emailCur
.getString(emailCur
.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
if(TextUtils.isEmpty(emailContact)||emailContact.equalsIgnoreCase(null)||emailContact.equalsIgnoreCase(""))
{
emailContact="";
Log.e("isEmpty","isEmpty " + emailContact);
}
else
{
Log.e("gfdszfg","Email " + emailContact);
}
/* emailType = emailCur
.getString(emailCur
.getColumnIndex(ContactsContract.CommonDataKinds.Email.TYPE));*/
Log.e("gfdszfg","Email " + emailContact);
}
emailCur.close();
}
if (image_uri != null)
{
System.out.println(Uri.parse(image_uri));
try
{
bitmap = MediaStore.Images.Media
.getBitmap(this.getContentResolver(),
Uri.parse(image_uri));
System.out.println(bitmap);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
mList.add(new Contacts(name, phone, image_uri,emailContact));
emailContact="";
}
cur.close();
mMyContactsAdapter = new MyContactsAdapter(MainActivity.this, mList);
mcontact.setAdapter(mMyContactsAdapter);
}
and more over in my code my contact fetching while loop is looping 3 times i dont know why.
I have faced this situation as you are in right now. Try below code
public static ArrayList ReadContactsSpecialWay(Context context) {
StringBuffer contactBuffer = new StringBuffer();
StringBuffer emailBuffer = new StringBuffer();
ArrayList<String> contactList = new ArrayList<>();
ArrayList<String> emailList = new ArrayList<>();
ArrayList<ContactModel> contactModelsList = new ArrayList<>();
HashMap<Integer, Boolean> hashMap = new HashMap<Integer, Boolean>();
String[] emailsAndContacts = new String[2];
// Phone numbers
Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
String[] projection = new String[]{
ContactsContract.CommonDataKinds.Phone.CONTACT_ID,
ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.NUMBER
};
Cursor phoneNumbers = context.getContentResolver().query(uri, projection, null, null, null);
int indexContactID = phoneNumbers.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID);
int indexName = phoneNumbers.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
int indexNumber = phoneNumbers.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
while (phoneNumbers.moveToNext()) {
Integer contactId = phoneNumbers.getInt(indexContactID);
String contactName = phoneNumbers.getString(indexName);
String contactNumber = phoneNumbers.getString(indexNumber).replace(" ", "");
ContactModel contactModel = new ContactModel();
contactModel.setContactPhone(contactNumber);
contactNumber = contactModel.getContactPhone();
if (hashMap.containsKey(contactId))
contactModel.setContactName(contactName + " (" + contactNumber + ")");
else {
hashMap.put(contactId, true);
contactModel.setContactName(contactName);
}
contactModelsList.add(contactModel);
contactList.add(contactNumber);
LogHelper.informationLog(contactNumber + " " + contactName);
contactBuffer.append(contactNumber + ",");
}
phoneNumbers.close();
// Emails
uri = ContactsContract.CommonDataKinds.Email.CONTENT_URI;
projection = new String[]{
ContactsContract.CommonDataKinds.Email.CONTACT_ID,
ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Email.DATA
};
Cursor emails = context.getContentResolver().query(uri, projection, null, null, null);
indexContactID = emails.getColumnIndex(ContactsContract.CommonDataKinds.Email.CONTACT_ID);
indexName = emails.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
int indexData = emails.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA);
while (emails.moveToNext()) {
Integer contactId = emails.getInt(indexContactID);
String contactName = emails.getString(indexName);
String contactEmail = emails.getString(indexData).toLowerCase();
ContactModel contactModel = new ContactModel();
contactModel.setEmailAddress(contactEmail);
if (hashMap.containsKey(contactId)) {
contactModel.setEmailName(contactName + " (" + contactEmail + ")");
} else {
contactModel.setEmailName(contactName);
hashMap.put(contactId, true);
}
contactModelsList.add(contactModel);
if (contactEmail != null && !emailList.contains(contactEmail)) {
emailList.add(contactEmail);
LogHelper.informationLog(contactEmail + " " + contactName);
emailBuffer.append(contactEmail + ",");
}
}
emails.close();
if (contactBuffer.toString().length() > 0) {
emailsAndContacts[0] = contactBuffer.toString().substring(0, (contactBuffer.toString().length() - 1));
} else
emailsAndContacts[0] = "";
if (emailBuffer.toString().length() > 0) {
emailsAndContacts[1] = emailBuffer.toString();
} else {
emailsAndContacts[1] = "";
}
if(contactModelsList.size() == 0)
return null;
else {
ArrayList specialList = new ArrayList();
specialList.add(contactModelsList);
specialList.add(emailsAndContacts);
return specialList;
}
}
It will definitely help you out.
Try this, using AsyncTask. Use it while launching apps default activity on background and fetch the array while using on another activity
class LoadContact extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... voids) {
// Get Contact list from Phone
Uri CONTENT_URI = ContactsContract.Contacts.CONTENT_URI;
String _ID = ContactsContract.Contacts._ID;
String DISPLAY_NAME = ContactsContract.Contacts.DISPLAY_NAME;
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();
/**
* #discussion Query contact and return name and contact Id.
*/
Cursor cursor = contentResolver.query(CONTENT_URI, null, null, null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC");
if (cursor.getCount() > 0) {
while (cursor.moveToNext()) {
Bitmap bit_thumb = null;
String contact_id = cursor.getString(cursor.getColumnIndex(_ID));
String name = cursor.getString(cursor.getColumnIndex(DISPLAY_NAME));
String image_thumb = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.PHOTO_THUMBNAIL_URI));
Cursor phoneCursor = contentResolver.query(PhoneCONTENT_URI, null, Phone_CONTACT_ID + " = ?", new String[]{contact_id}, null);
try {
if (image_thumb != null) {
bit_thumb = MediaStore.Images.Media.getBitmap(contentResolver, Uri.parse(image_thumb));
}
} catch (IOException e) {
e.printStackTrace();
}
while (phoneCursor.moveToNext()) {
String phoneNumber = phoneCursor.getString(phoneCursor.getColumnIndex(NUMBER));
final SelectUser selectUser = new SelectUser();
selectUser.setName(name);
selectUser.setContactId(contact_id + "" + phoneNumber);
selectUser.setThumb(bit_thumb);
selectUser.setPhone(phoneNumber);
if (selectUser.getPhone() != null && selectUser.getPhone().length() > 0 && !num.equalsIgnoreCase(phoneNumber)) {
num = phoneNumber;
selectUsers.add(selectUser);
}
}
phoneCursor.close();
Cursor cur1 = contentResolver.query(
ContactsContract.CommonDataKinds.Email.CONTENT_URI, null,
ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?",
new String[]{contact_id}, null);
while (cur1.moveToNext()) {
String email = cur1.getString(cur1.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
final SelectUser selectUser = new SelectUser();
selectUser.setName(name);
selectUser.setContactId(contact_id + "" + email);
selectUser.setThumb(bit_thumb);
selectUser.setEmail(email);
if (selectUser.getEmail() != null && selectUser.getEmail().length() > 0 && !userEmail.equalsIgnoreCase(email)) {
userEmail=email;
selectUsers.add(selectUser);
}
}
cur1.close();
}
}
cursor.close();
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
isContactLoaded = true;
}
}
I had written a code to fetch contact name, phone number and image from Contacts and to display it on a listview in android. It's working fine but taking more time to load. I had tried to use multi-threading in some parts of the code. But the loading time is not decreased.
Here is the onCreate() method:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lvDetail = (ListView) findViewById(R.id.listView1);
fetchcontacts();
lvDetail.setAdapter(new MyBaseAdapter(context, myList));
}
Here is the code for fetch contacts:
private void fetchcontacts() {
// TODO Auto-generated method stub
Cursor cursor = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null,
null, null, ContactsContract.Contacts.DISPLAY_NAME + " ASC");
int count = cursor.getCount();
if (count > 0) {
Toast.makeText(context, "count >0", Toast.LENGTH_SHORT).show();
while (cursor.moveToNext()) {
String columnId = ContactsContract.Contacts._ID;
int cursorIndex = cursor.getColumnIndex(columnId);
String id = cursor.getString(cursorIndex);
name = cursor.getString(cursor
.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
Toast.makeText(context, "Toast 1", Toast.LENGTH_SHORT).show();
int numCount = Integer.parseInt(cursor.getString(cursor
.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER)));
if (numCount > 0) {
Toast.makeText(context, "Toast 2", Toast.LENGTH_SHORT).show();
Cursor phoneCursor = getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null,
CommonDataKinds.Phone.CONTACT_ID+" = ?", new String[] { id
}, ContactsContract.Contacts.DISPLAY_NAME + " ASC");
while (phoneCursor.moveToNext()) {
Toast.makeText(context, "Toast 3", Toast.LENGTH_SHORT).show();
phoneNo = phoneCursor.getString(phoneCursor
.getColumnIndex(ContactsContract.CommonDataKinds.
Phone.NUMBER));
String image_uri = phoneCursor
.getString(phoneCursor
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.PHOTO_URI));
if (image_uri != null) {
Toast.makeText(context, "Toast 4", Toast.LENGTH_SHORT).show();
System.out.println(Uri.parse(image_uri));
try {
bitmap = MediaStore.Images.Media
.getBitmap(this.getContentResolver(),
Uri.parse(image_uri));
// sb.append("\n Image in Bitmap:" + bitmap);
// System.out.println(bitmap);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Toast.makeText(context, name, Toast.LENGTH_SHORT).show();
getDataInList(name,phoneNo,bitmap);
name=null;
phoneNo=null;
Drawable myDrawable = getResources().getDrawable(R.drawable.star1);
bitmap = ((BitmapDrawable) myDrawable).getBitmap();
}
phoneCursor.close();
}
}
}
Here the setAdapter() function of the listview is working after fetching all the contacts to an ArrayList. do anyone have idea about how to display the contacts during fetching contacts? any sample code?
1.Read the Columns from the Cursor which you required only ,According to your requirement you just need _ID,HAS_PHONE_NUMBER,DISPLAY_NAME ,so change the Cursor reading
Cursor cursor = getContentResolver().query(
ContactsContract.Contacts.CONTENT_URI,
new String[] { ContactsContract.Contacts._ID,
ContactsContract.Contacts.HAS_PHONE_NUMBER,
ContactsContract.Contacts.DISPLAY_NAME }, null, null,
ContactsContract.Contacts.DISPLAY_NAME + " ASC");
2.Dont do the time taking process in the UI thread..Use AsyncTask instead
Note : This two steps will resolve to some extent..but not completely
I made it by reduce repeated query wich is expensive. Best of my solution is that method found all mobile phones and email for each contact and insert to list for every contact values. It is fast as storm now :)
//contact entity
public class MobileContact {
public String name;
public String contact;
public Type type;
public MobileContact(String contact, Type type) {
name = "";
this.contact = contact;
this.type = type;
}
public MobileContact(String name, String contact, Type type) {
this.name = name;
this.contact = contact;
this.type = type;
}
public enum Type {
EMAIL, PHONE
}
#Override
public String toString() {
return "MobileContact{" +
"name='" + name + '\'' +
", contact='" + contact + '\'' +
", type=" + type +
'}';
}
}
// method for collect contacts
public List<MobileContact> getAllContacts() {
log.debug("get all contacts");
List<MobileContact> mobileContacts = new ArrayList<>();
ContentResolver contentResolver = context.getContentResolver();
// add all mobiles contact
Cursor phonesCursor = contentResolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, new String[]{ContactsContract.CommonDataKinds.Phone.NUMBER, ContactsContract.CommonDataKinds.Phone.CONTACT_ID}, null, null, null);
while (phonesCursor != null && phonesCursor.moveToNext()) {
String contactId = phonesCursor.getString(phonesCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID));
String phoneNumber = phonesCursor.getString(phonesCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)).replace(" ", "");
mobileContacts.add(new MobileContact(contactId, phoneNumber, MobileContact.Type.PHONE));
}
if (phonesCursor != null) {
phonesCursor.close();
}
// add all email contact
Cursor emailCursor = contentResolver.query(ContactsContract.CommonDataKinds.Email.CONTENT_URI, new String[]{ContactsContract.CommonDataKinds.Email.DATA, ContactsContract.CommonDataKinds.Email.CONTACT_ID}, null, null, null);
while (emailCursor != null && emailCursor.moveToNext()) {
String contactId = emailCursor.getString(emailCursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.CONTACT_ID));
String email = emailCursor.getString(emailCursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
mobileContacts.add(new MobileContact(contactId, email, MobileContact.Type.EMAIL));
}
if (emailCursor != null) {
emailCursor.close();
}
// get contact name map
Map<String, String> contactMap = new HashMap<>();
Cursor contactsCursor = contentResolver.query(ContactsContract.Contacts.CONTENT_URI, new String[]{ContactsContract.Contacts._ID, ContactsContract.Contacts.DISPLAY_NAME, ContactsContract.Contacts.HAS_PHONE_NUMBER}, null, null, ContactsContract.Contacts.DISPLAY_NAME);
while (contactsCursor != null && contactsCursor.moveToNext()) {
String contactId = contactsCursor.getString(contactsCursor.getColumnIndex(ContactsContract.Contacts._ID));
String contactName = contactsCursor.getString(contactsCursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
contactMap.put(contactId, contactName);
}
if (phonesCursor != null) {
phonesCursor.close();
}
// replace contactId to display name
for (MobileContact mobileContact : mobileContacts) {
String displayName = contactMap.get(mobileContact.name);
mobileContact.name = displayName != null ? displayName : "";
}
// sort list by name
Collections.sort(mobileContacts, new Comparator<MobileContact>() {
#Override
public int compare(MobileContact c1, MobileContact c2) {
return c1.name.compareTo(c2.name);
}
});
return mobileContacts;
}
The contacts in larse size use in backround task.
Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(number[i]));
ContentResolver contentResolver = getContentResolver();
Cursor search = contentResolver.query(uri, new String[]{ContactsContract.PhoneLookup._ID,
ContactsContract.PhoneLookup.DISPLAY_NAME}, null, null, null);
try {
if (search != null && search.getCount() > 0) {
search.moveToNext();
name = search.getString(search.getColumnIndex(ContactsContract.Data.DISPLAY_NAME));
id = search.getString(search.getColumnIndex(ContactsContract.Data._ID));
System.out.println("name" + name + "id" + id);
/* tv_name.setText(name);
tv_id.setText(id);
tv_phone.setText(number);*/
}
} finally {
if (search != null) {
search.close();
}
}
Fastest way for me soo far .
ContentResolver cr = mContext.getContentResolver(); Cursor cursor= mContext.getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, PROJECTION, "HAS_PHONE_NUMBER <> 0", null, null); if (cursor!= null) { final int displayNameIndex = cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME); final int numberIndex = cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER); final int idIndex= cursor.getColumnIndex(ContactsContract.Contacts._ID); String displayName, number = null, idValue; while (cursor.moveToNext()) {
displayName = cursor.getString(displayNameIndex);
idValue= cursor.getString(idIndex);
Cursor phones = mContext.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, "contact_id = '" + idValue + "'", null, null);
phones.moveToFirst();
try {
number = phones.getString(phones.getColumnIndex("data1"));
}
catch (CursorIndexOutOfBoundsException e)
{`
}
phones.close();
userList.add(new ContactModel(displayName , number , null , }
I want to know if its possible to fetch contacts which exist in SIM card or phonebook only. Right now I am using the following code to fetch contacts and it fetches all the contacts even my gmail and Facebook Contacts.
Cursor cursor = getContentResolver().query(
ContactsContract.Contacts.CONTENT_URI, null, null, null, Phone.DISPLAY_NAME + " ASC");
if (cursor.getCount() > 0)
{
while (cursor.moveToNext())
{
PhoneBookUserEntity user = new PhoneBookUserEntity();
// Pick out the ID, and the Display name of the
// contact from the current row of the cursor
user.setId(cursor.getString(cursor.getColumnIndex(BaseColumns._ID)));
user.setPhoneBookName(cursor.getString(cursor.getColumnIndex(
ContactsContract.Contacts.DISPLAY_NAME)));
if(user.getphonebookname().length() > 4)
username = user.getphonebookname();//.substring(0,4);
else
username = user.getphonebookname();//.substring(0,1);
String hasPhone = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
// if (Boolean.parseBoolean(hasPhone)) {
Cursor phones = getContentResolver().query( ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = "+ user.getId(), null, null);
while (phones.moveToNext()) {
user.sePhoneNumber(phones.getString(phones.getColumnIndex( ContactsContract.CommonDataKinds.Phone.NUMBER)));
}
phones.close();
//}
// user.sePhoneNumber(cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)));
Cursor emails = getContentResolver().query(ContactsContract.CommonDataKinds.Email.CONTENT_URI, null, ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = " + user.getId(), null, null);
while (emails.moveToNext()) {
// This would allow you get several email addresses
user.setEmailAddress(emails.getString(emails.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA)));
}
emails.close();
user.setImageURI(getPhotoUri(user.getId()));
SearchContactsActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
_progressDialog.setMessage("Copying over your local phone book. Retrieving contact information for \n"+ username.toUpperCase());
}
});
arraylist.add(user);
}
}
cursor.close();
For Sim contact only you can use below code
private void allSIMContact()
{
try
{
String ClsSimPhonename = null;
String ClsSimphoneNo = null;
Uri simUri = Uri.parse("content://icc/adn");
Cursor cursorSim = this.getContentResolver().query(simUri,null,null,null,null);
Log.i("PhoneContact", "total: "+cursorSim.getCount());
while (cursorSim.moveToNext())
{
ClsSimPhonename =cursorSim.getString(cursorSim.getColumnIndex("name"));
ClsSimphoneNo = cursorSim.getString(cursorSim.getColumnIndex("number"));
ClsSimphoneNo.replaceAll("\\D","");
ClsSimphoneNo.replaceAll("&", "");
ClsSimPhonename=ClsSimPhonename.replace("|","");
Log.i("PhoneContact", "name: "+ClsSimPhonename+" phone: "+ClsSimphoneNo);
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
Cursor cursor = getContacts();
getBundleValues2();
String displayName = "";
while (cursor.moveToNext()) {
//taking id name and phone number from contacts using content provider
String displayid = cursor.getString(cursor
.getColumnIndex(ContactsContract.Contacts._ID));
displayName = cursor.getString(cursor
.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
String displayphnno = "";
ContentResolver cr = getContentResolver();
if (Integer.parseInt(cursor.getString(cursor
.getColumnIndex(ContactsContract.Data.HAS_PHONE_NUMBER))) > 0) {
Cursor pCur = cr.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID
+ " = ?", new String[] { displayid }, null);
while (pCur.moveToNext()) {
displayphnno = pCur
.getString(pCur
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER))
+ "\n";
ContactProviderViewGroup v6;
//using view group appending it to an activity
if (colorFlag) {
v6 = new ContactProviderViewGroup(this, displayName,
displayphnno, passedid, colorFlag);
colorFlag = false;
} else {
v6 = new ContactProviderViewGroup(this, displayName,
displayphnno, passedid, colorFlag);
colorFlag=true;
}
LL1.addView(v6);
}
pCur.close();
}
}
}
private void getBundleValues2() {
Intent i = getIntent();
Bundle myBundle = i.getExtras();
if (myBundle != null) {
passedid = myBundle.getInt("gid");
}
}
private Cursor getContacts() {
// Run query
Uri uri = ContactsContract.Contacts.CONTENT_URI;
String[] projection = new String[] { ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.Contacts.HAS_PHONE_NUMBER };
String selection = ContactsContract.Contacts.IN_VISIBLE_GROUP + " = '"
+ ("1") + "'";
String[] selectionArgs = null;
String sortOrder = ContactsContract.Contacts.DISPLAY_NAME
+ " COLLATE LOCALIZED ASC";
return managedQuery(uri, projection, selection, selectionArgs,
sortOrder);
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Intent intentContact = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(intentContact, PICK_CONTACT);
}
public void onActivityResult(int requestCode, int resultCode, Intent intent)
{
if (requestCode == PICK_CONTACT)
{
getContactInfo(intent);
System.out.println("HASPHONE NUMBER"+phoneNumber);
// Your class variables now have the data, so do something with it.
}
}//onActivityResult
protected void getContactInfo(Intent intent)
{
Cursor cursor = managedQuery(intent.getData(), null, null, null, null);
while (cursor.moveToNext())
{
String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
name = cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME));
String hasPhone = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
if ( hasPhone.equalsIgnoreCase("1"))
hasPhone = "true";
else
hasPhone = "false" ;
if (Boolean.parseBoolean(hasPhone))
{
Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = "+ contactId,null, null);
while (phones.moveToNext())
{
phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
}
phones.close();
}
// Find Email Addresses
Cursor emails = getContentResolver().query(ContactsContract.CommonDataKinds.Email.CONTENT_URI,null,ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = " + contactId,null, null);
while (emails.moveToNext())
{
String emailAddress = emails.getString(emails.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
}
emails.close();
Cursor address = getContentResolver().query(
ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.StructuredPostal.CONTACT_ID + " = " + contactId,
null, null);
while (address.moveToNext())
{
// These are all private class variables, don't forget to create them.
String poBox = address.getString(address.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.POBOX));
String street = address.getString(address.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.STREET));
String city = address.getString(address.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.CITY));
String state = address.getString(address.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.REGION));
String postalCode = address.getString(address.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE));
String country = address.getString(address.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.COUNTRY));
String type = address.getString(address.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.TYPE));
} //address.moveToNext()
} //while (cursor.moveToNext())
cursor.close();
}
}
protected void getContactInfo(Intent intent)
{
String number[];
Cursor cursor = managedQuery(intent.getData(), null, null, null, null);
number=new String[cursor.getCount()];
int numCount=0;
while (cursor.moveToNext())
{
String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
name = cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME));
String hasPhone = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
if ( hasPhone.equalsIgnoreCase("1"))
hasPhone = "true";
else
hasPhone = "false" ;
if (Boolean.parseBoolean(hasPhone))
{
Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = "+ contactId,null, null);
while (phones.moveToNext())
{
phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
if(phoneNumber.startsWith("011")) number[numCount++]=phoneNumber;
}
phones.close();
}
// Find Email Addresses
Cursor emails = getContentResolver().query(ContactsContract.CommonDataKinds.Email.CONTENT_URI,null,ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = " + contactId,null, null);
while (emails.moveToNext())
{
String emailAddress = emails.getString(emails.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
}
emails.close();
Cursor address = getContentResolver().query(
ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.StructuredPostal.CONTACT_ID + " = " + contactId,
null, null);
while (address.moveToNext())
{
// These are all private class variables, don't forget to create them.
String poBox = address.getString(address.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.POBOX));
String street = address.getString(address.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.STREET));
String city = address.getString(address.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.CITY));
String state = address.getString(address.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.REGION));
String postalCode = address.getString(address.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE));
String country = address.getString(address.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.COUNTRY));
String type = address.getString(address.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.TYPE));
} //address.moveToNext()
} //while (cursor.moveToNext())
cursor.close();
}
}