I am using the following code to retrieve the contacts first and last name list from android however i also want to retrieve the email simultaneously:
Cursor1 = getContentResolver().query(
public List<String> getFullContactName()
{
List<String> name = new ArrayList<String>();
String[] projection = new String[] {Data.DATA2, Data.DATA3};
String where = Data.MIMETYPE + "='" + StructuredName.CONTENT_ITEM_TYPE + "'";
Uri uri = Data.CONTENT_URI;
ContentResolver contentResolver = getApplicationContext().getContentResolver();
Cursor cursor = contentResolver.query(uri,projection,where,null,null);
String firstName, lastName;
while (cursor.moveToNext())
{
firstName = cursor.getString(cursor.getColumnIndex(Data.DATA2));
lastName = cursor.getString(cursor.getColumnIndex(Data.DATA3));
name.add(firstName + " " + lastName);
Toast.makeText(getApplicationContext(), "First name"+firstName, Toast.LENGTH_LONG).show();
Toast.makeText(getApplicationContext(), "Second name"+lastName, Toast.LENGTH_LONG).show();
}
cursor.close();
cursor = null;
return name;
}
Cursor emails = getContentResolver().query(ContactsContract.CommonDataKinds.Email.CONTENT_URI, null, ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = " + contactId, null, null);
while (emails.moveToNext()) {
// This would allow you get several email addresses
String emailAddress = emails.getString(
emails.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
}
emails.close();
}
cursor.close();
I need to know how can i read first name ,last name email, phone number together using a single Cursor because i need to fetch details in a list and then display them in a listview. I havent got a reference where i can fetch the details using a single cursor.
Use below code for get contact details.
public void getContacts(ContentResolver cr) {
ArrayList<HashMap<String, String>> mContacts = new ArrayList<HashMap<String, String>>();
HashMap<String, String> mTempObj = new HashMap<String, String>();
cur = cr.query(ContactsContract.CommonDataKinds.Email.CONTENT_URI,
null, null, null, null);
cur.moveToFirst();
if (cur.getCount() > 0) {
for (int i = 0; i < cur.getCount(); i++) {
mTempObj.add("Email", cur.getString(cur.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA)));
cur.moveToNext();
}
}
cur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null, null, null, null);
cur.moveToFirst();
if (cur.getCount() > 0) {
for (int i = 0; i < cur.getCount(); i++) {
mTempObj.add("Number", cur.getString(cur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DATA)));
cur.moveToNext();
}
}
cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null,
null);
cur.moveToFirst();
if (cur.getCount() > 0) {
for (int i = 0; i < cur.getCount(); i++) {
mTempObj.add("Name", cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)));
cur.moveToNext();
}
}
cur = cr.query(ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_URI,
null, null, null, null);
cur.moveToFirst();
if (cur.getCount() > 0) {
for (int i = 0; i < cur.getCount(); i++) {
mTempObj.add("Address", cur.getString(cur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.STREET)));
mTempObj.add("City", cur.getString(cur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.CITY)));
mTempObj.add("State", cur.getString(cur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.REGION)));
cur.moveToNext();
}
}
mContacts.add(mTempObj);
}
it will solve your problem.
remove
cursor.close();
cursor = null;
and make sure that the contactId that you passed to the Cursor emails is the same as the one that you retrieved from Cursor cursor which seems that you did not declare it in your String[] projection
For the first projection you can as follow:
String[] projection = new String[] {
ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME};
this projection will retrive the contact Id and contact name, then to get the contact id and Name
String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
String Name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
Then the second projection could be somthing:
String[] projection2= new String[]{
Email.ADDRESS,
Email.TYPE
Then define second cursor to get email within the first cursor something like
Cursor cur2 = cr.query(emailURI,projection2,Email.CONTACT_ID + "=" +id,null,null);
where id is the id that you got from first cursor.
Hope this help
Related
I am using the below code to fetch the local phone contacts. It is working fine and also fetching the contacts very fast.
But the problem comes here, in my contact list there are few contacts that are having multiple Emails and multiple phone numbers.
In case of multiple phone or emails address it repeats the name of the same person multiple times.
And if i change
ContactsContract.CommonDataKinds.Email.CONTENT_URI
to ContactsContract.CommonDataKinds.Phone.CONTENT_URI then it will repeat name according to the number of phone number exists for a contact. Please help
private static final String[] PROJECTION = new String[]{
ContactsContract.CommonDataKinds.Email.CONTACT_ID,
ContactsContract.CommonDataKinds.Nickname.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Email.DATA,
ContactsContract.CommonDataKinds.Phone.NUMBER,
};
ContentResolver cr = mContext.getContentResolver();
Cursor cursor = cr.query(ContactsContract.CommonDataKinds.Email.CONTENT_URI, PROJECTION, null, null, null);
if (cursor != null) {
try {
final int contactIdIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.CONTACT_ID);
final int displayNameIndex = cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
final int emailIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA);
final int phoneIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
long contactId;
String displayName, email, phone, photo;
while (cursor.moveToNext()) {
mNK_UserModel = new NK_Contact();
contactId = cursor.getLong(contactIdIndex);
displayName = cursor.getString(displayNameIndex);
//Adding display name
mNK_UserModel.setFirstName(displayName);
Util.DEBUG_LOG(1, "contact", "contact id :" + contactId);
al_PhoneContacts.add(mNK_UserModel);
}
} finally {
cursor.close();
}
}
If i had to guess i would say you are missing a "break" in your while-loop. Since the cursor tries to fetch the next available column entry. But have a look at my solution which worked for me in the past.
It uses a seperate cursor for each row which gives you more control over the data.
Map<String, String> contactDataMap = new HashMap<String, String>();
Uri contactData = data.getData();
Cursor cursor = getContentResolver().query(contactData, null, null, null, null);
cursor.moveToFirst();
String name = cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME));
String id = cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.Contacts._ID));
contactDataMap.put(NAME, (name != null)?name:"");
if (Integer.parseInt(cursor.getString(
cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
Cursor pCur = getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
new String[]{id},
null);
while (pCur.moveToNext()) {
String number = pCur.getString(pCur.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.NUMBER));
contactDataMap.put(PHONE, (number != null)?number:"");
break;
}
pCur.close();
}
Cursor emailCur = getContentResolver().query(
ContactsContract.CommonDataKinds.Email.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?",
new String[]{id}, null);
while (emailCur.moveToNext()) {
String email = emailCur.getString(
emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
contactDataMap.put(MAIL, (email != null)?email:"");
break;
}
emailCur.close();
cursor.close();
I have the following code to load all contacts with their phones and pictures on samsung s3 device.
public static void getAllContactWithNumberAndNameAndPhoto(Context context,
ArrayList<ContactInfo> mContactList, boolean starred) {
ContentResolver cr = context.getContentResolver();
Cursor cur = null;
if (starred == true) {
cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null,
"starred=?", new String[] { "1" }, null);
} else {
cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null,
null, null);
}
if (cur.getCount() > 0) {
while (cur.moveToNext()) {
ContactInfo item = new ContactInfo();
String id = cur.getString(cur
.getColumnIndex(ContactsContract.Contacts._ID));
String name = cur
.getString(cur
.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
// Uri photo = PhoneUtils.getPhotoUriFromID(context, id);
String starredValue = cur.getString(cur
.getColumnIndex(ContactsContract.Contacts.STARRED));
boolean isFav = false;
if (starredValue.equals("1"))
isFav = true;
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);
while (pCur.moveToNext()) {
String phoneNo = pCur
.getString(pCur
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
item.addPhone(removeCharactersFromPhoneNumber(phoneNo));
}
pCur.close();
// if (photo != null) {
//
// item.setPhoto(photo.toString());
// }
item.setName(name);
item.setFavorite(isFav);
item.setRecent(false);
mContactList.add(item);
}
}
cur.close();
}
}
when I run this code on 1000 contacts it takes about 40 second to load
when I remove the part of loading multiple phones for the same 1000 contact, it takes about 1.5 second.
Can any one tell me if there is an efficient way to load contacts phone and not let the user to wait all this time.
Try this:
private Cursor getContacts() {
// Run query
Uri uri = ContactsContract.Contacts.CONTENT_URI;
String[] projection = new String[] { ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME, ContactsContract.Contacts.PHOTO_URI, ContactsContract.Contacts.PHOTO_THUMBNAIL_URI, ContactsContract.CommonDataKinds.Phone.CONTENT_URI }; // put the items u need here
String selection = ContactsContract.Contacts.IN_VISIBLE_GROUP + " = '"
+ ("1") + "'";
String[] selectionArgs = null;
String sortOrder = ContactsContract.Contacts.DISPLAY_NAME
+ " COLLATE LOCALIZED ASC";
return getContentResolver().query(uri, projection, selection, selectionArgs,
sortOrder);
}
i want to select unique contacts from android only that contacts which have phone numbers. i am using this code
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null,
null, null, ContactsContract.Contacts.DISPLAY_NAME);
// Find the ListView resource.
mainListView = (ListView) findViewById(R.id.mainListView);
// When item is tapped, toggle checked properties of CheckBox and
// Planet.
mainListView
.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent, View item,
int position, long id)
{
ContactsList planet = listAdapter.getItem(position);
planet.toggleChecked();
PlanetViewHolder viewHolder = (PlanetViewHolder) item
.getTag();
viewHolder.getCheckBox().setChecked(planet.isChecked());
}
});
// Create and populate planets.
planets = (ContactsList[]) getLastNonConfigurationInstance();
// planets = new Planet[10];
// planets.Add("asdf");
ArrayList<ContactsList> planetList = new ArrayList<ContactsList>();
String phoneNumber = null;
String phoneType = null;
count = cur.getCount();
contacts = new ContactsList[count];
if (planets == null)
{
if (cur.getCount() > 0)
{
planets = new ContactsList[cur.getCount()];
int i = 0;
//
while (cur.moveToNext())
{
String id = cur.getString(cur
.getColumnIndex(ContactsContract.Contacts._ID));
String name = cur
.getString(cur
.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
if (Integer
.parseInt(cur.getString(cur
.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0)
{
// Query phone here. Covered next
Cursor pCur = cr
.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID
+ " = ?", new String[]
{ id }, null);
// WHILE WE HAVE CURSOR GET THE PHONE NUMERS
while (pCur.moveToNext())
{
// Do something with phones
phoneNumber = pCur
.getString(pCur
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DATA));
phoneType = pCur
.getString(pCur
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE));
Log.i("Pratik", name + "'s PHONE :" + phoneNumber);
Log.i("Pratik", "PHONE TYPE :" + phoneType);
}
pCur.close();
}
planets = new ContactsList[]
{ new ContactsList(name, phoneNumber) };
contacts[i] = planets[0];
planetList.addAll(Arrays.asList(planets));
i++;
}
}
this code retrieve all the contacts and put the into a list. but i want unique contacts and only that which have phone no. how can i do this?? is there any method to pass some argument in query to select unique contacts only???
I think you mean you got duplicate record for some contacts. So you must add condition for your query. The essential part is contacts must be in visible group and have phone number.
String selection = ContactsContract.Contacts.IN_VISIBLE_GROUP + " = '"
+ ("1") + "'";
String sortOrder = ContactsContract.Contacts.DISPLAY_NAME
+ " COLLATE LOCALIZED ASC";
cur = context.getContentResolver().query(
ContactsContract.Contacts.CONTENT_URI, projection, selection
+ " AND " + ContactsContract.Contacts.HAS_PHONE_NUMBER
+ "=1", null, sortOrder);// this query only return contacts which had phone number and not duplicated
Update 20/05/2020
suspend fun fetchContacts(): ArrayList<FriendItem> {
val list = ArrayList<FriendItem>()
val uri: Uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI
val selection = ContactsContract.Contacts.HAS_PHONE_NUMBER
val cursor: Cursor? = context.contentResolver.query(
uri,
arrayOf(
ContactsContract.CommonDataKinds.Phone.NUMBER,
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone._ID,
ContactsContract.Contacts._ID
),
selection,
null,
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC"
)
cursor?.let {
val nameIndex = cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)
val phoneIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)
while (cursor.moveToNext()) {
val info = FriendItem(
friendName = cursor.getString(nameIndex),
friendPhoneNumber = cursor.getString(phoneIndex)
)
list.add(info)
}
cursor.close()
}
return list
}
This is working for me to get contact with phone number. Here we are querying Data table, and using CONTACT_ID contact provider documentation
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
final String ORDER_BY = ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME_PRIMARY + " ASC";
final String[] PROJECTION = {
ContactsContract.CommonDataKinds.Phone.CONTACT_ID,
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME_PRIMARY,
ContactsContract.CommonDataKinds.Phone.NUMBER
};
return new CursorLoader(
context,
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
PROJECTION,
null,
null,
ORDER_BY
);
}
easy way to get phonenumbers and contact names
// set as global
Set<string> phonenumbersList = new HashSet<string>();
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));
//contact has name number and phonenumber does not exists in list
if ( phoneNumber != null && name != null && !phonenumbersList.contains(phoneNumber)){
planets = new ContactsList[]{ new ContactsList(name, phoneNumber) };
phonenumbersList.add(phoneNumber);
planetList.addAll(Arrays.asList(planets));
planetList.Add(phoneNumber, name);
}
}
phones.close();
I am using android 2.1 platform.The code I have will display the Name number and email ID of all the persons from the Emulator contact list,by using this code I will get the requirement as on above.I have some contacts in my emulator, I created two more contacts (say C and D). BUT the issues are
Issue 1. If I create a new contact having name and number not email, This contact will take the email ID from the contact just down to it.for eg: if I create a name C has no email ID but D has email ID, D is the contact already in the Emulator. C will take D's email ID.C and D have same email ID.
Issue 2. If again I create a new contact having name email but not number, This contact will take the number from the contact I previously created.for eg: if I create the name E has no number but it will take the number of the contact C. so C and E have the same number .
I am using this code
public class GetAllDatas extends Activity {
ListView lvItem;
private Button btnAdd;
String displayName="", emailAddress="", phoneNumber="";
ArrayList<String> contactlist=new ArrayList<String>();
ArrayAdapter<String> itemAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
lvItem = (ListView)this.findViewById(R.id.lvitems);
btnAdd = (Button)this.findViewById(R.id.btnAddItem);
itemAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,contactlist);
lvItem.setAdapter(itemAdapter);
btnAdd.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
readContacts();
}
});
}
private void readContacts()
{
ContentResolver cr =getContentResolver();
Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
while (cursor.moveToNext())
{
displayName = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
Cursor emails = cr.query(Email.CONTENT_URI,null,Email.CONTACT_ID + " = " + id, null, null);
while (emails.moveToNext())
{
emailAddress = emails.getString(emails.getColumnIndex(Email.DATA));
break;
}
emails.close();
if(Integer.parseInt(cursor.getString(cursor.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);
while (pCur.moveToNext())
{
phoneNumber = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
break;
}
pCur.close();
}
// To display the Details
contactlist.add(displayName+", "+phoneNumber+", "+ emailAddress+"\n");
itemAdapter.notifyDataSetChanged();
}
Collections.sort(contactlist);
cursor.close();
}
}
How can I solve this problem ?
As i Understand your question..
Before add new item in reference variables just erase the previous one..
like,
emailAddress = "" ;
displayName = "" ;
phoneNumber = "" ;
in your while loop for fetching contact information and adding it to list..
private void readContacts()
{
ContentResolver cr =getContentResolver();
Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
while (cursor.moveToNext())
{
emailAddress = "" ;
displayName = "" ;
phoneNumber = "" ;
displayName = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
Cursor emails = cr.query(Email.CONTENT_URI,null,Email.CONTACT_ID + " = " + id, null, null);
while (emails.moveToNext())
{
emailAddress = emails.getString(emails.getColumnIndex(Email.DATA));
break;
}
emails.close();
if(Integer.parseInt(cursor.getString(cursor.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);
while (pCur.moveToNext())
{
phoneNumber = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
break;
}
pCur.close();
}
// To display the Details
contactlist.add(displayName+", "+phoneNumber+", "+ emailAddress+"\n");
}
Collections.sort(contactlist);
itemAdapter.notifyDataSetChanged();
cursor.close();
}
try this one ..........
public void readContacts(){
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
null, null, null, null);
contactName=new String[cur.getCount()];
contactNumber=new String[cur.getCount()][];
contactEmail=new String[cur.getCount()][];
int i=0;
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));
contactName[i]=name;
Log.e("Contact Name",contactName[i]);
if (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
// get the phone number
Cursor pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = ?",
new String[]{id}, null);
contactNumber[i]=new String[pCur.getCount()];
int j=0;
while (pCur.moveToNext()) {
String phone = pCur.getString(
pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
contactNumber[i][j]=phone;
Log.d("Contact number",contactNumber[i][j]);
j++;
}
pCur.close();
}
// get email and type
Cursor emailCur = cr.query(
ContactsContract.CommonDataKinds.Email.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?",
new String[]{id}, null);
contactEmail[i]=new String[emailCur.getCount()];
int k=0;
while (emailCur.moveToNext()) {
String email = emailCur.getString(
emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
String emailType = emailCur.getString(
emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.TYPE));
contactEmail[i][k]=email;
Log.v("Contact email",contactEmail[i][k]);
k++;
}
emailCur.close();
}
} i++;
}
I would like to query on phonenumber to obtain the rawcontactID.
The only thing I know of the contact is the given phonenumber, but for my function I need to have the rawcontactID. I got a working code but now I did use 2 seperate queries. What I would like to have is 1 query that can do both just to save some query time.
my code:
Uri uri = Uri.withAppendedPath(Phone.CONTENT_FILTER_URI, Uri.encode(phoneNumber));
String[] columns = new String[]{Phone.CONTACT_ID, Phone.DISPLAY_NAME, Phone.NUMBER, Phone._ID };
Cursor cursor = contentResolver.query(uri, columns, null, null, null);
if(cursor!=null) {
int clenght = cursor.getCount();
while(cursor.moveToNext()){
//contactName = cursor.getString(cursor.getColumnIndexOrThrow(PhoneLookup.DISPLAY_NAME));
id = cursor.getString(cursor.getColumnIndex(Phone.CONTACT_ID));
}
cursor.close();
}
Cursor pCur = contentResolver.query(ContactsContract.Data.CONTENT_URI, new String[]{ContactsContract.Data.RAW_CONTACT_ID}, ContactsContract.Data.CONTACT_ID+" = "+ id, null, null);
if(pCur!=null) {
int clenght = pCur.getCount();
while(pCur.moveToNext()){
//contactName = cursor.getString(cursor.getColumnIndexOrThrow(PhoneLookup.DISPLAY_NAME));
id = pCur.getString(pCur.getColumnIndex(ContactsContract.Data.RAW_CONTACT_ID));
}
pCur.close();
}
thanks in advance
Edit:
My code above works fine, but I am still looking for increasing speed for large number of contacts. Therefore I will give a bounty if someone comes with a solution to combine my queries.
private String[] getRawContactIdFromNumber(String givenNumber){
List<String> rawIds = new ArrayList<String>();
Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, new String[]{ContactsContract.CommonDataKinds.Phone.RAW_CONTACT_ID},ContactsContract.CommonDataKinds.Phone.NUMBER + "='"+ givenNumber +"'",null, ContactsContract.CommonDataKinds.Phone.NUMBER);
while (phones.moveToNext())
{
rawIds.add( phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.RAW_CONTACT_ID)));
Log.v("contacts","Given Number: " + givenNumber + "Raw ID: " +rawIds.get(rawIds.size() - 1));
}
phones.close();
String[] ret = new String[0];
return rawIds.toArray(ret);
}
Edited to only include the raw id in the cursor for efficiency. Also changed return type to array in case multiple contacts have the same number.
Please try
String phonenumber = "input your phone number";
Cursor pCur = getContentResolver().query(
ContactsContract.Data.CONTENT_URI,
new String[] { ContactsContract.Data.RAW_CONTACT_ID,
Phone.CONTACT_ID }, Phone.NUMBER + " = " + phonenumber,
null, null);
if (pCur != null) {
while (pCur.moveToNext()) {
String contactID = pCur.getString(pCur
.getColumnIndex(Phone.CONTACT_ID));
String Rowid = pCur.getString(pCur
.getColumnIndex(ContactsContract.Data.RAW_CONTACT_ID));
Log.e("RAW_CONTACT_ID", Rowid);
Log.e("CONTACT_ID", contactID);
}
pCur.close();
}
Now you can get Both CONTACT_ID & RAW_CONTACT_ID in single query.