folks!
Look I broke my mind with problem -
how get display_name from ContactContract via _ID I got earlier???
Here is the code:
public static long getId(Context context, String number) {
long id = 0;
String displayName;
// define the columns I want the query to return
final String[] projection = new String[] {
ContactsContract.PhoneLookup.DISPLAY_NAME,
ContactsContract.PhoneLookup._ID};
// encode the phone number and build the filter URI
final Uri contactUri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(number));
// query time
final Cursor cursor = context.getContentResolver().query(contactUri, projection, null, null, null);
if(cursor != null) {
if (cursor.moveToFirst()) {
displayName = cursor.getString(cursor.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME));
// HERE IS GOOD _ID!
id = cursor.getLong(cursor.getColumnIndex(ContactsContract.PhoneLookup._ID));
Log.d("_TAG_", displayName);
{
//
// v. N-1
//
Cursor cursor2 = context.getContentResolver().query(
contactUri,
projection,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
new String[]{String.valueOf(id)}, null);
if(cursor2 != null) {
// Cursor valid but string below got error "android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 1 : )"
displayName = cursor2.getString(cursor.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME));
Log.d("_TAG_", displayName);
}
}
{
//
// v. N
//
Uri myPhoneUri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI,
Uri.encode(String.valueOf(id)));
Cursor phoneCursor = context.getContentResolver().query(
myPhoneUri, null, null, null, null);
for (phoneCursor.moveToFirst(); !phoneCursor.isAfterLast(); phoneCursor.moveToNext()) {
// No steps inside!
String str = phoneCursor.getString(phoneCursor
.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Nickname.NAME));
Log.d(App.LOG_TAG, "ContactUtils.getId: " + str);
}
if(phoneCursor != null) {
phoneCursor.close();
}
}
} else {
Log.d("_TAG_", "Contact Not Found # " + number);
}
cursor.close();
}
return id;
}
"v.N-1" and "v.N" are just 2 ones from a million attempts before.
See - I got _ID, so why it doesn't work back as valid query???
Here is decision i found.
public static String getDisplayName(Context context, long id) {
String displayName = null;
// define the columns I want the query to return
final String[] projection = new String[] {
ContactsContract.Contacts.DISPLAY_NAME,
};
final Cursor cursor = context.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, projection,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[] { id + "" }, null);
if(cursor != null) {
if (cursor.moveToFirst()) {
displayName = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
}
cursor.close();
}
return displayName;
}
It works...
Related
I have function to load all contact number in android, and now i want to filter all contact number with prefix "0878","0877","0817" so contact number with that prefix will be loaded, and here my current code :
private void loadContact(){
ContentResolver cr = applicationContext.getContentResolver();
String [] PROJECTION = ContactsQuery.PROJECTION;
Cursor cursor = cr.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
PROJECTION,
null,
null,
null
);
while (cursor.moveToNext()) {
//String name = cursor.getString(ContactsQuery.DISPLAY_NAME);
String lookUpKey = cursor.getString(ContactsQuery.LOOKUP_KEY);
loadContactDetail(lookUpKey);
}
cursor.close();
}
private void loadContactDetail(String lookUpKey){
ContentResolver cr = applicationContext.getContentResolver();
String [] COLS = {ContactsContract.CommonDataKinds.Phone.NUMBER};
Cursor cursor = cr.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI, COLS,
ContactsContract.Data.LOOKUP_KEY + " = ?",
new String[]{lookUpKey},
null
);
while (cursor.moveToNext()) {
String phone = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
String formatted = Util.formatMSISDN(phone);
if(formatted != null)
contactsSet.add(formatted);
}
cursor.close();
}
Try this.
while (cursor.moveToNext()) {
String phone = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
String formatted = Util.formatMSISDN(phone);
if(formatted != null){
if(formatted.startsWith("0878") || formatted.startsWith("0877") || formatted.startsWith("0817"))
contactsSet.add(formatted);
}
}
cursor.close();
Check out the sourceString.contains(CharSequence) method.
I'm trying to import contacts into my app, but struggling with getting the company name. Here's my code:
public List<ContactItem> getContactList(){
ArrayList<ContactItem> contactList = new ArrayList<ContactItem>();
Uri contactUri = ContactsContract.Contacts.CONTENT_URI;
String[] PROJECTION = new String[] {
ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.Contacts.HAS_PHONE_NUMBER,
};
String SELECTION = ContactsContract.Contacts.HAS_PHONE_NUMBER + "='1'";
Cursor contacts = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, PROJECTION, SELECTION, null, null);
if (contacts.getCount() > 0)
{
while(contacts.moveToNext()) {
ContactItem aContact = new ContactItem();
int idFieldColumnIndex = 0;
int nameFieldColumnIndex = 0;
int numberFieldColumnIndex = 0;
int companyFieldColumnIndex = 0;
String contactId = contacts.getString(contacts.getColumnIndex(ContactsContract.Contacts._ID));
nameFieldColumnIndex = contacts.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME);
if (nameFieldColumnIndex > -1)
{
aContact.setName(contacts.getString(nameFieldColumnIndex));
}
// Tried to get a company, but
// this always returns -1
companyFieldColumnIndex = contacts.getColumnIndex(ContactsContract.CommonDataKinds.Organization.COMPANY);
if (companyFieldColumnIndex > -1)
{
Log.d(TAG, "getContactList: starts");
aContact.setCompany(contacts.getString(companyFieldColumnIndex));
}
PROJECTION = new String[] {ContactsContract.CommonDataKinds.Phone.NUMBER};
final Cursor phone = managedQuery(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, PROJECTION, ContactsContract.Data.CONTACT_ID + "=?", new String[]{String.valueOf(contactId)}, null);
if(phone.moveToFirst()) {
while(!phone.isAfterLast())
{
numberFieldColumnIndex = phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
if (numberFieldColumnIndex > -1)
{
aContact.setPhoneNum(phone.getString(numberFieldColumnIndex));
phone.moveToNext();
TelephonyManager mTelephonyMgr;
mTelephonyMgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
if (!mTelephonyMgr.getLine1Number().contains(aContact.getPhoneNum()))
{
contactList.add(aContact);
}
}
}
}
phone.close();
}
contacts.close();
}
return contactList;
}
I add a comment in my code, where i'm trying to get the contact's company name, but i always get -1. Some contacts have the company name, so something wrong in this part of code. How to get the company properly?
First thing, you are passing Projection which doesn't contains anything related to Company name so of course you won't get it.
Other thing which I am not sure is, you need to pass contact's RawId instead of ID to fetch the Company name. Here's something how you should do it,
String contactId = contacts.getString(contacts.getColumnIndex(ContactsContract.Contacts._ID));
String rawContactId = getRawContactId(contactId);
String companyName = getCompanyName(rawContactId);
& here are the functions you'll need:
private String getRawContactId(String contactId) {
String[] projection = new String[]{ContactsContract.RawContacts._ID};
String selection = ContactsContract.RawContacts.CONTACT_ID + "=?";
String[] selectionArgs = new String[]{contactId};
Cursor c = mContentResolver.query(ContactsContract.RawContacts.CONTENT_URI, projection, selection, selectionArgs, null);
if (c == null) return null;
int rawContactId = -1;
if (c.moveToFirst()) {
rawContactId = c.getInt(c.getColumnIndex(ContactsContract.RawContacts._ID));
}
c.close();
return String.valueOf(rawContactId);
}
and:
private String getCompanyName(String rawContactId) {
try {
String orgWhere = ContactsContract.Data.RAW_CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?";
String[] orgWhereParams = new String[]{rawContactId,
ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE};
Cursor cursor = mContentResolver.query(ContactsContract.Data.CONTENT_URI,
null, orgWhere, orgWhereParams, null);
if (cursor == null) return null;
String name = null;
if (cursor.moveToFirst()) {
name = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Organization.COMPANY));
}
cursor.close();
return name;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
In my application I try to search a contact using the phonenumber. The phonenumber I am searching with is always in the same format ('123456789' for example).
But the following code retrieves not all contacts I expected.
The main issue might be the different format of phonenumbers in my phone: some contacts are saved with '+12 345 6789', the other with '0123 456789'.
Although I tried ContactsContract.PhoneLookup.NORMALIZED_NUMBER my code retrieves only the contacts saved with phonenumbers in the '123456789'-format.
private String getContactDetails(Context context, String number) {
String[] projection = new String[] {
ContactsContract.PhoneLookup.DISPLAY_NAME,
ContactsContract.PhoneLookup._ID,
ContactsContract.PhoneLookup.LOOKUP_KEY};
int len = number.length();
Uri contactUri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(number.substring(len-7)));
String selection = null;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) {
selection = ContactsContract.PhoneLookup.NORMALIZED_NUMBER + " LIKE %" + number.substring(len-7) + "%";
}
Cursor cursor = context.getContentResolver().query(contactUri, projection, selection, null, null);
String name = null;
if(cursor != null) {
if (cursor.moveToFirst()) {
name = cursor.getString(cursor.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME));
}
cursor.close();
}
return name;
}
Don't use both PhoneLookup.CONTENT_FILTER_URI with selection, CONTENT_FILTER_URIs are used to search for data using the URI itself, and should not get any selection.
The PhoneLookup.NORMALIZED_NUMBER column is for getting the result back in an e164 format, not for querying.
Try this:
Uri uri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode("123456789"));
String[] projection = new String[] { PhoneLookup.NUMBER, PhoneLookup.NORMALIZED_NUMBER };
Cursor c = getContentResolver().query(uri, projection, null, null, null);
if (c != null) {
if (c.moveToFirst()) {
String number = c.getString(0);
String e164_number = c.getString(1);
Log.d(TAG, "number=" + number + ", e164=" + e164_number);
} else {
Log.d(TAG, "couldn't find number");
}
}
c.close();
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);
}
I'm trying to delete all contacts from a defined group but I don't know how to do a join from the contact table and group table (if it's possible).
ContentResolver cr = getContentResolver();
String where = ContactsContract.Groups.TITLE + " =='LolGroup'";
Cursor cursor = cr.query(
ContactsContract.Contacts.CONTENT_URI, null, where, null, null);
while (cursor.moveToNext()) {
String lookupKey = cursor.getString(
cursor.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));
Uri uri = Uri.withAppendedPath(
ContactsContract.Contacts.CONTENT_LOOKUP_URI, lookupKey);
cr.delete(uri, null, null);
}
Of course it gives me an error because there is no "title" in the contacts group, but if I do a join with the ID I should get what i want.
Any idea how to do that join?
It looks strange because ContactsContract.Contacts does not have ContactsContract.Groups.TITLE column. So I think that you can get group id with the group title you want and then search contacts with the group id. The idea might go like following:
public String getGroupIdByTitle(String groupTitle){
try {
cursor = mContentResolver.query(
ContactsContract.Groups.CONTENT_URI,
new String[] {Groups._ID},
Groups.TITLE + "=?",
new String[]{groupTitle},
null);
while (cursor.moveToNext()){
return cursor.getString(cursor.getColumnIndex(0);
}
} finally {
if (cursor!=null) cursor.close();
}
return "";
}
public String getGroupIdOfContact(String lookupKey) {
String where = String.format("%s=? AND %s=?", Data.LOOKUP_KEY, Data.MIMETYPE);
String[] whereArgs = {lookupKey, GroupMembership.CONTENT_ITEM_TYPE};
String groupRowId = "";
Cursor cursor = mContentResolver.query(
Data.CONTENT_URI,
new String[]{GroupMembership.GROUP_ROW_ID},
where, whereArgs, null);
try {
if (cursor.moveToNext()) {
return cursor.getString(cursor.getColumnIndex(GroupMembership.GROUP_ROW_ID));
}
} finally {
if (cursor!=null) cursor.close();
}
return "";
}
public void deleteContactByGroupTitle(String groupTitle) {
String targetGroupId = getGroupIdByTitle(groupTitle);
Cursor cursor = null;
try {
cursor = mContentResolver.query(Contacts.CONTENT_URI, null, null, null, null);
while (cursor.moveToNext()){
String lookupKey = cursor.getString(cursor.getColumnIndex(Contacts.LOOKUP_KEY));
String groupId = getGroupIdOfContact(lookupKey);
if (targetGroupId.equals(groupId)){
//TODO. delete this contact
}
}
} finally {
if (cursor!=null) cursor.close();
}
}
The above code has not tested but I think that basic idea would be same.