I.m new to Android Contact's, I wanted to return a contact id/ contact from below URi:
content://com.android.contacts/contacts/lookup/encoded?directory=2147483647#{\"display_name\":\"\u202A9500249707\u202C\",\"display_name_source\":20,\"vnd.android.cursor.item\\/contact\":{\"vnd.android.cursor.item\\/phone_v2\":[{\"data1\":\"123456789\"}
]}}
which is start with encoded?directory=2147483647..
can any one suggestion me here!!
In order to fetch the contact from the external storage of the phone, we have to understand about content Resolver,Cursor which you can learn on the android documentation.As you have asked in question, to handle the contact and it's related data, we can use following code.
Uri contactUri = data.getData();
Cursor cursor = null;
try {
String phoneNo = null;
cursor = getContentResolver()
.query(contactUri, null, null, null, null);
if (cursor.getCount() == 0) return;
cursor.moveToFirst();
String name = cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME));
int phoneIndex = cursor.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.NUMBER);
phoneNo = cursor.getString(phoneIndex);
} finally {
cursor.close();
}
From this sample code,We can extract the necessary data using content Resolver and content provider.
But first, we have to pass content uri through intent as below to use the above code.
pickContact = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
Related
So I've written a query to extract the WhatsApp contacts of a phone. My initial query goes like this:
Cursor c = con.getContentResolver().query(
ContactsContract.RawContacts.CONTENT_URI,
new String[]{ContactsContract.RawContacts.CONTACT_ID, ContactsContract.RawContacts.DISPLAY_NAME_PRIMARY},
ContactsContract.RawContacts.ACCOUNT_TYPE + "= ?",
new String[]{"com.whatsapp"},
null
);
ArrayList<String> myWhatsappContacts = new ArrayList<String>();
int contactNameColumn = c.getColumnIndex(ContactsContract.RawContacts.DISPLAY_NAME_PRIMARY);
while (c.moveToNext()) {
// You can also read RawContacts.CONTACT_ID to read the
// ContactsContract.Contacts table or any of the other related ones.
myWhatsappContacts.add(c.getString(contactNameColumn));
}
The purpose of this is to find out how many WhatsApp contacts the phone has at any one time. When I do:
Log.i("WhatsApp contacts found:", Integer.toString(myWhatsappContacts.size());
It should print out how many WhatsApp contacts there were into LogCat. And this works - up to a point.
Let's say for example that the number of WhatsApp contacts I have now is 101. The next phase of this little project is to delete away ALL contacts if there are more than 100 of them. In which case, we go:
if (myWhatsappContacts.size() > 100) {
//Delete all contacts code here
}
I've tested the delete contacts code, it works. I check the contacts directory of the phone via the contacts app, and it says 0. But now when I do the query again (refer to code above), it still shows 101! What's going on?
If it helps, my DeleteContacts method is as follows:
private void deleteContact(Context ctx, String phone, String name) {
Uri contactUri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phone));
Cursor cur = ctx.getContentResolver().query(contactUri, null, null, null, null);
try {
if (cur.moveToFirst()) {
do {
if (cur.getString(cur.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME)).equalsIgnoreCase(name)) {
String lookupKey = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));
Uri uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_LOOKUP_URI, lookupKey);
ctx.getContentResolver().delete(uri, null, null);
return;
}
} while (cur.moveToNext());
}
} catch (Exception e) {
System.out.println(e.getStackTrace());
} finally {
cur.close();
}
return;
}
What am I doing wrong? Is my DeleteContacts code faulty? Or is the query itself faulty?
my app creates new contacts with ContentProviderOperation. The problem is, I need a reference to the new contact because I need some information of it to display it in a listview and go with intent into the contact app to the contact.
The best thing would be the ID, but I´ve read that it might change during operations on the database, which won´t be helpful to me.
Now I thought, the Uri might be the best thing, because I could later retrieve the contactID or lookup key.
How do I get the Uri directly after calling applyBatch() ?
EDIT:
Here is a solution, but not really a good one.
He is putting a randomly generated token into each contact, then he makes a new query with it.
I want neither put some extra data into the contacts, nor starting a second query. But if there is no other possibility I´ll do it that way.
simply call
private String retrieveContactId(String phoneNo) {
try {
Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phoneNo));
String[] projection = new String[] { ContactsContract.PhoneLookup._ID, ContactsContract.PhoneLookup.DISPLAY_NAME };
String selection = null;
String[] selectionArgs = null;
String sortOrder = ContactsContract.PhoneLookup.DISPLAY_NAME + " COLLATE LOCALIZED ASC";
ContentResolver cr = getApplicationContext().getApplicationContext().getContentResolver();
String contactId = null;
if (cr != null) {
Cursor resultCur = cr.query(uri, projection, selection, selectionArgs, sortOrder);
if (resultCur != null) {
while (resultCur.moveToNext()) {
contactId = resultCur.getString(resultCur.getColumnIndex(ContactsContract.PhoneLookup._ID));
Log.e("Info Incoming", "Contact Id : " + contactId);
return contactId;
}
resultCur.close();
}
}
} catch (Exception sfg) {
Log.e("Error", "Error in loadContactRecord : " + sfg.toString());
}
return null;
}
and for the uri
Uri contactUri = Contacts.getLookupUri(
Integer.valueOf(rawContactId), clookup);
I want to display the native android contacts list and then once the user picks a contact, i would like to move to the next native screen where it shows the details of the contact (like phone numbers, email, etc).
Now once the user selects either an email address or a phone number, I would then like to get that data back to my original activity and do further processing.
I know that I could use
startActivityForResult(new Intent(Intent.ACTION_PICK, Contacts.CONTENT_URI), REQUEST_CODE_PICK_CONTACT);
and then myself parse the contact using getContentResolver().query() and then store each of the required fields. Then finally display on a separate activity as contact details and then once the user chooses any one of the phone numbers or emails, then i use that to do further processing.
I tried to do the following inside onActivityResult():
Uri contactData = data.getData();
Intent intent = new Intent(Intent.ACTION_PICK, contactData);
startActivityForResult(intent, REQUEST_CODE_PICK_CONTACT_DETAIL);
This displays the details of the contact but when the user selects a particular number, android calls it instead of passing it back to me in the previous activity.
But I would like to use the native screens if possible and it would require a lot less parsing and no extra activities/fragments.
Could someone suggest how to go about doing this?
Thanks
You can get contact details from phone contact doing this way
Uri uri = data.getData();
String[] projection = new String[] {ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.NUMBER};
Cursor people = getActivity().getContentResolver().query(uri, projection, null, null, null);
int indexName = people.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
int indexNumber = people.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
int type = people.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE);
people.moveToFirst();
do {
String name = people.getString(indexName);
String number = people.getString(indexNumber);
System.out.println(name+number);
} while (people.moveToNext());
This might help:
Uri contactData = data.getData();
ContentResolver cr = getContentResolver();
Cursor c = cr.query(contactData, null, null, null, null);
if (c.moveToFirst()) {
String id = c
.getString(c
.getColumnIndexOrThrow(ContactsContract.Contacts._ID));
String hasPhone = c
.getString(c
.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
if (hasPhone.equalsIgnoreCase("1")) {
Cursor phones = getContentResolver()
.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID
+ " = " + id, null, null);
phones.moveToFirst();
String cNumber = phones
.getString(phones
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
Toast.makeText(getApplicationContext(), cNumber,
Toast.LENGTH_SHORT).show();
String nameContact = c
.getString(c
.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME));
// contact number = cNumber
//contact name = nameContact
}
}
I query the phone's calllog into a ListView. So when the user long clicks an item, a dialog comes up with options, including "View contact". To be able to view the contact the intent needs the contact id.
My problem is that I not always get to see the right contact. I click on Peter, and Peter's contact sheet comes up. I click on Sarah, and Jason's contact sheet comes up.
I must have been using this code the wrong way. Please help.
ContentResolver contentResolver = getContentResolver();
Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phone));
Cursor cursor = contentResolver.query(uri, new String[] {PhoneLookup.DISPLAY_NAME, PhoneLookup._ID}, null, null, null);
if(cursor!=null) {
while(cursor.moveToNext())
{
String contactName = cursor.getString(cursor.getColumnIndexOrThrow(PhoneLookup.DISPLAY_NAME));
contactid2 = cursor.getString(cursor.getColumnIndexOrThrow(PhoneLookup._ID));
}
cursor.close();
}
Intent intent_contacts = new Intent(Intent.ACTION_VIEW, Uri.parse("content://contacts/people/" + contactid2));
startActivity(intent_contacts);
Maybe what I need is not the PhoneLookup._ID, but some other ID.
I also tried Felipe's answer here, same happens.
Edit:
on a HTC Desire HD (2.3.5) I get the proper contacts in 99% of the
cases.
on a ZTE Blade (2.2) I get the proper contacts in 60% of the cases.
on a Samsung Galaxy Ace (2.3.3) I get the proper contacts in 5% of the cases.
What the hell is going on???
After digging myself into theme, I found sven's help on googlegroups. The problem was that I was using a depracated intent. I read through many pages on the developer site, I must have missed it somehow.
I also post the full code.
contactid26 = null;
ContentResolver contentResolver = getContentResolver();
Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phonenumintolist));
Cursor cursor =
contentResolver.query(
uri,
new String[] {PhoneLookup.DISPLAY_NAME, PhoneLookup._ID},
null,
null,
null);
if(cursor!=null) {
while(cursor.moveToNext()){
String contactName = cursor.getString(cursor.getColumnIndexOrThrow(PhoneLookup.DISPLAY_NAME));
contactid26 = cursor.getString(cursor.getColumnIndexOrThrow(PhoneLookup._ID));
}
cursor.close();
}
if (contactid26 == null) {
Toast.makeText(DetailedCallHistory.this, "No contact found associated with this number", Toast.LENGTH_SHORT).show();
}
else {
Intent intent_contacts = new Intent(Intent.ACTION_VIEW, Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_URI, String.valueOf(contactid26)));
//Intent intent_contacts = new Intent(Intent.ACTION_VIEW, Uri.parse("content://contacts/people/" + contactid26));
startActivity(intent_contacts);
}
Here in this case i am going to show you that how to get the ID, and
Name of any contact no, which you have enter and want to search, For
Example if you enter a no and want to search its Name and id then use
this code, it is working 100%, if you want further modification in
this, then you can tell me
Uri lookupUri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI,Uri.encode(phnno.getText().toString()));//phone no
String[] proj = new String[]
{///as we need only this colum from a table...
Contacts.DISPLAY_NAME,
Contacts._ID,
};
String id=null;
String sortOrder1 = StructuredPostal.DISPLAY_NAME + " COLLATE LOCALIZED ASC";
Cursor crsr = getContentResolver().query(lookupUri,proj, null, null, sortOrder1);
while(crsr.moveToNext())
{
String name=crsr.getString(crsr.getColumnIndex(Contacts.DISPLAY_NAME));
id = crsr.getString(crsr.getColumnIndex(Contacts._ID));
Toast.makeText(this,"Name of this cntct is : " +name +"\n id is : "+id ,Toast.LENGTH_SHORT).show();
}
crsr.close();
In my app, user writes a phone number, and I want to find the contact name with that phone number?
I usually search the contacts like this:
Cursor cur = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI,
null, null, null, null);
But I do this to access all contacts... In this app I only want to get the contact name of the given phone number... How can I restrict the query?
Or do I have to go trough all contacts and see if any has the given phone number? But I believe that this can be very slow this way...
If you want the complete code:
public String getContactDisplayNameByNumber(String number) {
Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(number));
String name = "?";
ContentResolver contentResolver = getContentResolver();
Cursor contactLookup = contentResolver.query(uri, new String[] {BaseColumns._ID,
ContactsContract.PhoneLookup.DISPLAY_NAME }, null, null, null);
try {
if (contactLookup != null && contactLookup.getCount() > 0) {
contactLookup.moveToNext();
name = contactLookup.getString(contactLookup.getColumnIndex(ContactsContract.Data.DISPLAY_NAME));
//String contactId = contactLookup.getString(contactLookup.getColumnIndex(BaseColumns._ID));
}
} finally {
if (contactLookup != null) {
contactLookup.close();
}
}
return name;
}
You should have a look at the recommended ContactsContract.PhoneLookup provider
A table that represents the result of looking up a phone number, for example for caller ID. To perform a lookup you must append the number you want to find to CONTENT_FILTER_URI. This query is highly optimized.
Uri uri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phoneNumber));
resolver.query(uri, new String[]{PhoneLookup.DISPLAY_NAME,...