Getting contactdetails from contact Id not working in android - android

Hello i am working on a contact directory,i have made a custom call logs,Noe i want to display the contact details when one of the contact is clicked,I have first fetched contact_id from the contact number,and then by searching over the internet i got a function to get all details from contact id,I have put it in my code,But its not working,not giving me results,
public void getDetials(String contactID) {
Uri myPhoneUri = Uri.withAppendedPath(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
Uri.encode(contactID));
// Query the table
#SuppressWarnings("deprecation")
Cursor phoneCursor = managedQuery(myPhoneUri, null, null, null, null);
// Get the phone numbers from the contact
for (phoneCursor.moveToFirst(); !phoneCursor.isAfterLast(); phoneCursor
.moveToNext()) {
// Get a phone number
String phoneNumber = phoneCursor
.getString(phoneCursor
.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.NUMBER));
//get name
String phonename = phoneCursor
.getString(phoneCursor
.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME));
//get email
String phoneemail = phoneCursor
.getString(phoneCursor
.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Email.DATA));
//get image uri..!!
String img_uri = phoneCursor
.getString(phoneCursor
.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.PHOTO_URI));
System.out
.println("=============my phone number ,is==================="
+ phoneNumber + "======in call info=="+"\n =========name is===="+phonename+"=================email is========"+phoneemail);
System.out.println("======myimgae url fopr the contact is============="+img_uri);
}
}

Here is method to read all phone numbers and emails for specified contact:
public void getContactDetails(int contactId) {
Log.d("Details", "---");
Log.d("Details", "Contact : " + contactId);
final Cursor phoneCursor = getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
new String[] {
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.NUMBER,
ContactsContract.CommonDataKinds.Phone.PHOTO_URI,
},
Data.CONTACT_ID + "=?",
new String[] {String.valueOf(contactId)}, null);
try {
final int idxAvatarUri = phoneCursor.getColumnIndexOrThrow(
ContactsContract.CommonDataKinds.Phone.PHOTO_URI);
final int idxName = phoneCursor.getColumnIndexOrThrow(
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
final int idxPhone = phoneCursor.getColumnIndexOrThrow(
ContactsContract.CommonDataKinds.Phone.NUMBER);
while (phoneCursor.moveToNext()) {
String phoneNumber = phoneCursor.getString(idxPhone);
String name = phoneCursor.getString(idxName);
String avatarUri = phoneCursor.getString(idxAvatarUri);
Log.d("Details", "Phone number: " + phoneNumber);
Log.d("Details", "Name: " + name);
Log.d("Details", "Avatar URI: " + avatarUri);
}
} finally {
phoneCursor.close();
}
final Cursor emailCursor = getContentResolver().query(
ContactsContract.CommonDataKinds.Email.CONTENT_URI,
new String[] {
ContactsContract.CommonDataKinds.Email.ADDRESS,
},
Data.CONTACT_ID + "=?",
new String[] {String.valueOf(contactId)}, null);
try {
final int idxAddress = emailCursor.getColumnIndexOrThrow(
ContactsContract.CommonDataKinds.Email.ADDRESS);
while (emailCursor.moveToNext()) {
String address = emailCursor.getString(idxAddress);
Log.d("Details", "Email: " + address);
}
} finally {
emailCursor.close();
}
}
Please note that single contact can hold multiple phone numbers and emails.
Here is how to get all contacts details:
final Cursor cur = getContentResolver().query(Data.CONTENT_URI,
new String[]{Data.CONTACT_ID}, null, null, null);
try {
final int idxId = cur.getColumnIndex(Data.CONTACT_ID);
while (cur.moveToNext()) {
final int id = cur.getInt(idxId);
getContactDetails(id);
}
} finally {
cur.close();
}
Don't forget to add permission:
<uses-permission android:name="android.permission.READ_CONTACTS"/>

Related

Select one contact number from a list of multiple contact numbers

I want to fetch only the first contact number from a list of contact numbers of a particular user, with the help of cursor. Here is my code:
private ArrayList<ArrayList<String>> getAllContacts() {
ArrayList<ArrayList<String>> nameList = new ArrayList<ArrayList<String>>();
ArrayList<String> person=new ArrayList<>();
ArrayList<String> number=new ArrayList<>();
ArrayList<String> temp=new ArrayList<>();
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
null, null, null, null);
if ((cur!=null ? cur.getCount() : 0) > 0) {
while (cur!=null && cur.moveToNext()) {
String id = cur.getString(
cur.getColumnIndex(ContactsContract.Contacts._ID));
String name = cur.getString(cur.getColumnIndex(
ContactsContract.Contacts.DISPLAY_NAME));
person.add(name);
if (cur.getInt(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.getCount()==1) {
while (pCur.moveToNext()) {
String phoneNo = pCur.getString(pCur.getColumnIndex(
ContactsContract.CommonDataKinds.Phone.NUMBER));
number.add(phoneNo);
}
}
else{
while (pCur.moveToNext()) {
String phoneNo = pCur.getString(pCur.getColumnIndex(
ContactsContract.CommonDataKinds.Phone.NUMBER));
temp.add(phoneNo);
}
number.add(temp.get(0));
temp.clear();
}
pCur.close();
}
}
}
if (cur!=null) {
cur.close();
}
Log.d("contacts",String.valueOf(number.size())+" "+String.valueOf(person.size())); //the lists aren't of equal size
if(person.size()==number.size()){
nameList.add(person);
nameList.add(number);
}
else{
//don't know what to do here
}
return nameList;
}
But, the code still fetches multiple contact numbers saved for a single user, in other words person.size() is not equal to number.size(). What do I do?
The array sizes are not the same because not all contacts have phone-numbers, you are correctly checking for HAS_PHONE_NUMBER and only if true, getting that contact's phone numbers - which means number.size() would be < person.size() on most phones.
I would suggest instead of keeping separate Arrays for names and phones, having a single Array with a simple java class that represents a person.
Other than that, your code is very inefficient, as you're doing a ton of queries, while you can do just one.
Here's an example with the two suggestions above:
class Person {
long id,
String name,
String firstPhone;
public Person(id, name, firstPhone) {
this.id = id;
this.name = name;
this.firstPhone = firstPhone;
}
}
Map<Long, Person> mapping = new HashMap<>(); // mapping between a contact-id to a Person object
String[] projection = {Data.CONTACT_ID, Data.DISPLAY_NAME, Phone.NUMBER};
// query phones only
String selection = Data.MIMETYPE + "='" + Phone.CONTENT_ITEM_TYPE + "'";
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(Data.CONTENT_URI, projection, selection, null, null);
while (cur != null && cur.moveToNext()) {
long id = cur.getLong(0);
String name = cur.getString(1); // full name
String phone = cur.getString(2); // phone
Log.d(TAG, "got " + id + ", " + name + " - " + data);
// only add a new object if we haven't seen this person before
if (!mapping.containsKey(id)) {
Person person = new Person(id, name, phone);
mapping.put(id, person);
}
}
cur.close();
Array<Person> people = mapping.values();
EDIT
Set<Long> ids = new HashSet<Long>();
Array<String> names = new ArrayList<String>();
Array<String> numbers = new ArrayList<String>();
String[] projection = {Data.CONTACT_ID, Data.DISPLAY_NAME, Phone.NUMBER};
// query phones only
String selection = Data.MIMETYPE + "='" + Phone.CONTENT_ITEM_TYPE + "'";
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(Data.CONTENT_URI, projection, selection, null, null);
while (cur != null && cur.moveToNext()) {
long id = cur.getLong(0);
String name = cur.getString(1); // full name
String phone = cur.getString(2); // phone
Log.d(TAG, "got " + id + ", " + name + " - " + data);
// only add a new object if we haven't seen this person before
if (ids.add(id)) {
names.add(name);
numbers.add(phone);
}
}
cur.close();

Pick email, name, and phone number from contact picker intent

how can I get the email address correctly? Here's what I've done so far.
#android.webkit.JavascriptInterface
public void chooseContact(){
Intent pickContactIntent = new Intent(Intent.ACTION_PICK);
pickContactIntent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE);
startActivityForResult(pickContactIntent, CONTACT_PICKER_RESULT);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data){
if (requestCode == CONTACT_PICKER_RESULT){
Uri contactUri = data.getData();
// Perform the query.
// We don't need a selection or sort order (there's only one result for the given URI)
Cursor cursor = getContentResolver().query(contactUri, null, null, null, null);
cursor.moveToFirst();
// Retrieve the phone number from the NUMBER column.
int column = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
String phoneNumber = cursor.getString(column);
if(phoneNumber != null)
phoneNumber = phoneNumber.trim();
if(phoneNumber == null || phoneNumber.equals("")) {
// This should never happen, but just in case we'll handle it
Log.e(TAG, "Phone number was null!");
Util.debugAsserts(false);
return;
}
// Retrieve the contact name.
column = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Identity.DISPLAY_NAME);
String name = cursor.getString(column);
// Retrieve the contact email address.
column = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA);
String email = cursor.getString(column);
cursor.close();
JSONObject contacts = new JSONObject();
String jsonString;
try {
contacts.put("name" , name);
contacts.put("email" , email);
contacts.put("phoneNumber" , phoneNumber);
jsonString = contacts.toString();
String encodedData = Base64.encodeToString(jsonString.getBytes(), Base64.DEFAULT);
String command = String.format("get_contact_details('%s');", encodedData);
eaWebView.submitJavascript(command);
} catch (JSONException e) {
throw new Error(e);
}
}
}
The above code get the name and phone number correctly but the email returns as phone number not the email address from the contact.
Thank you in advance!
The problem is that you're using a Phone-picker in your code, by setting setType(Phone.CONTENT_TYPE) you're telling the contacts app you're only interested in a phone number.
You need to switch to a Contact-picker, like so:
Intent intent = new Intent(Intent.ACTION_PICK, Contacts.CONTENT_URI);
Then you read the result like this:
Uri contactData = data.getData();
// get contact-ID and name
String[] projection = new String[] { Contacts._ID, Contacts.DISPLAY_NAME };
Cursor cursor = getContentResolver().query(contactUri, projection, null, null, null);
cursor.moveToFirst();
long id = cursor.getLong(0);
String name = cursor.getString(1);
Log.i("Picker", "got a contact: " + id + " - " + name);
cursor.close();
// get email and phone using the contact-ID
String[] projection2 = new String[] { Data.MIMETYPE, Data.DATA1 };
String selection2 = Data.CONTACT_ID + "=" + id + " AND " + Data.MIMETYPE + " IN ('" + Phone.CONTENT_ITEM_TYPE + "', '" + Email.CONTENT_ITEM_TYPE + "')";
Cursor cursor2 = getContentResolver().query(Data.CONTENT_URI, projection2, selection2, null, null);
while (cursor2 != null && cursor2.moveToNext()) {
String mimetype = cursor2.getString(0);
String data = cursor2.getString(1);
if (mimetype.equals(Phone.CONTENT_ITEM_TYPE)) {
Log.i("Picker", "got a phone: " + data);
} else {
Log.i("Picker", "got an email: " + data);
}
}
cursor2.close();
You Can Use Below Method To Fetch Contact Number, Email and Contact Name
public static void getContactDetails(Context context){
ArrayList<String> names = new ArrayList<String>();
ContentResolver cr = context.getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,null, null, null, null);
if (cur.getCount() > 0) {
while (cur.moveToNext()) {
String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
Cursor cur1 = cr.query(
ContactsContract.CommonDataKinds.Email.CONTENT_URI, null,
ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?",
new String[]{id}, null);
while (cur1.moveToNext()) {
String name=cur1.getString(cur1.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String number=cur1.getString(cur1.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
String email = cur1.getString(cur1.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
Log.e("Contact Details","\n Name is :"+name+" Email is: "+ email+ " Number is: "+number);
if(email!=null){
names.add(name);
}
}
cur1.close();
}
}
See Below Image For Output

How to get email from contact

This code is working fine for fetching name and phone but i don't know how to get email from this code. Here is my code :
public static ArrayList<ContentValues> getContactDetails(final Context mContext){
ArrayList<ContentValues> contactList = new ArrayList<ContentValues>();
String order = ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC";
Cursor managedCursor = mContext.getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null,
null, order);
int _number = managedCursor
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
int _name = managedCursor
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
int _id = managedCursor
.getColumnIndex(ContactsContract.CommonDataKinds.Phone._ID);
while (managedCursor.moveToNext()) {
ContentValues values = new ContentValues();
Contact mContact = new Contact();
values.put(ContactClass.CONTACT_NAME, managedCursor.getString(_name));
values.put(ContactClass.CONTACT_MOBILE_NUMBER, managedCursor.getString(_number).replaceAll("\\s+",""));
mContact.setPhNo(managedCursor.getString(_number).replaceAll("\\s+",""));
mContact.setName(managedCursor.getString(_name));
contactList.add(values);
serverContactList.add(mContact);
}
}
return contactList;
}
here i want to get email and add to serverContactList list.
I edited your code, add rest of your code in 2 todos.
public static ArrayList<ContentValues> getContactDetails(final Context mContext) {
// todo rest of things
int _id = managedCursor
.getColumnIndex(ContactsContract.CommonDataKinds.Phone._ID);
while (managedCursor.moveToNext()) {
// we will get emails for a contact id
String id = managedCursor.getString(_id);
Cursor cur1 = mContext.getContentResolver().query(
ContactsContract.CommonDataKinds.Email.CONTENT_URI, null,
ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?",
new String[]{id}, null);
if (cur1 != null) {
while (cur1.moveToNext()) {
//to get the contact names
String name = cur1.getString(cur1.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
Log.e("Name :", name);
String email = cur1.getString(cur1.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
Log.e("Email", email);
}
}
cur1.close();
// todo rest of things
}
return contactList;
}
Don't use managedCursor, ever.
Query over Data.CONTENT_URI instead of Phone.CONTENT_URI to get access to all Data items (including Phone and Email and others if needed)
Limit the query by MIMETYPE to just the items you need
Map<Long, Contact> contacts = new HashMap<>();
String[] projection = {Data.CONTACT_ID, Data.DISPLAY_NAME, Data.MIMETYPE, Data.DATA1, Data.DATA2, Data.DATA3};
// query only emails/phones/events
String selection = Data.MIMETYPE + " IN ('" + Phone.CONTENT_ITEM_TYPE + "', '" + Email.CONTENT_ITEM_TYPE + "')";
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(Data.CONTENT_URI, projection, selection, null, null);
while (cur != null && cur.moveToNext()) {
long id = cur.getLong(0);
String name = cur.getString(1); // full name
String mime = cur.getString(2); // type of data (phone / email)
String data = cur.getString(3); // the actual info, e.g. +1-212-555-1234
Log.d(TAG, "got " + id + ", " + name + " - " + data);
// add info to existing list if this contact-id was already found, or create a new list in case it's new
Contact contact;
if (contacts.containsKey(id)) {
contact = contacts.get(id);
} else {
contact = new Contact();
contacts.put(id, contact);
contact.setName(name);
}
if (mime == Phone.CONTENT_ITEM_TYPE) {
contact.setPhNo(data);
} else {
contact.setEmail(data);
}
}

Method to return contacts phone number always returns null - Android [duplicate]

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;
}

Fetch Local phonebook contacts From SIM card only android

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);
}

Categories

Resources