I am trying to retrieve Phone Number hence using
String addrWhere = Contacts.Phones.NUMBER + " = " + userNumber;
String id = "";
Cursor c = mContext.getContentResolver().query(
Contacts.Phones.CONTENT_URI,
new String[] { Contacts.Phones._ID }, addrWhere, null, null);
try {
if (c.getCount() > 0) {
c.moveToFirst();
id = c.getString(0);
Log.i("IDS", id);
}
} finally {
c.close();
}
return id;
Can anyone let me know my mistake in this?
Try the solution to How to query ContactsContract.CommonDataKinds.Phone on Android? which is usage of ContactsContract.PhoneLookup provider:
Uri uri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phoneNumber));
resolver.query(uri, new String[]{PhoneLookup.DISPLAY_NAME,...
HI Every one...
thanks for reply!!! # Sotapanna
well i found the answer as pointed by Sotapanna
pasting the working code for anyone who needs it!
private String findID(String userNumber) {
Uri uri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri
.encode(userNumber));
int id = 0;
String[] returnVals = new String[] { PhoneLookup._ID };
Cursor pCur = mContext.getContentResolver().query(uri, returnVals,
PhoneLookup.NUMBER + " = \"" + userNumber + "\"", null, null);
if (pCur.getCount() > 0) {
pCur.moveToFirst();
id = pCur.getColumnCount();
if (id >= 0) {
id = pCur.getInt(0);
}
}
Log.i("Contacts", "" + id);
return String.valueOf(id);
}
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;
}
I know how to retrieve a user profile from the ContentResolver. If I have a bitmap, how can I set it as a user profile picture (replace it OR set it, if none exists)?
I load the user profile like following:
Uri dataUri = Uri.withAppendedPath(ContactsContract.Profile.CONTENT_URI, ContactsContract.Contacts.Data.CONTENT_DIRECTORY);
String[] selection = new String[]
{
ContactsContract.Profile._ID,
ContactsContract.Profile.DISPLAY_NAME,
ContactsContract.Profile.PHOTO_URI,
ContactsContract.Profile.LOOKUP_KEY
};
Cursor cursor = MainApp.get().getContentResolver().query(
dataUri,
selection,
null,
null,
null);
if (cursor != null)
{
int id = cursor.getColumnIndex(ContactsContract.Profile._ID);
int name = cursor.getColumnIndex(ContactsContract.Profile.DISPLAY_NAME);
int photoUri = cursor.getColumnIndex(ContactsContract.Profile.PHOTO_URI);
int lookupKey = cursor.getColumnIndex(ContactsContract.Profile.LOOKUP_KEY);
try
{
if (cursor.moveToFirst())
{
int phId = cursor.getInt(id);
mName = cursor.getString(name);
mImageUri = cursor.getString(photoUri);
mLookupKey = cursor.getString(lookupKey);
mExists = true;
}
}
finally
{
cursor.close();
}
}
Here's how to update or create profile images, actually it's working the same way as updating normal contact pictures. I had a problem somewhere else...
Instead of using my UserProfile, just exchange them and hand on the raw id.
private static void updatePhoto(UserProfile profile, Bitmap bitmap, ...)
{
byte[] photo = ImageUtil.convertImageToByteArray(bitmap, true);
ContentValues values = new ContentValues();
int photoRow = -1;
String where = ContactsContract.Data.RAW_CONTACT_ID + " = " + profile.getRawId() + " AND " + ContactsContract.Data.MIMETYPE + "=='" + ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE + "'";
Cursor cursor = MainApp.get().getContentResolver().query(ContactsContract.Data.CONTENT_URI, null, where, null, null);
int idIdx = cursor.getColumnIndexOrThrow(ContactsContract.Data._ID);
if (cursor.moveToFirst()) {
photoRow = cursor.getInt(idIdx);
}
cursor.close();
values.put(ContactsContract.Data.RAW_CONTACT_ID, profile.getRawId());
values.put(ContactsContract.Data.IS_SUPER_PRIMARY, 1);
values.put(ContactsContract.CommonDataKinds.Photo.PHOTO, photo);
values.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE);
if (photoRow >= 0) {
MainApp.get().getContentResolver().update(ContactsContract.Data.CONTENT_URI, values, ContactsContract.Data._ID + " = " + photoRow, null);
} else {
MainApp.get().getContentResolver().insert(ContactsContract.Data.CONTENT_URI, values);
}
...
}
I was recently playing around with some code that goes through my contacts and creates an identicon for any contact that does not have a photo set. For the most part this ended up working quite well but for some reason I have a handful of contacts that will not update. Log output says it is creating the photo. The update() returns 1 indicating 1 row was updated and stepping through the code for a contact that never seems to show the new photo looks good.
The fact that only a select few are not updating is what is really bugging me and I'm guessing there must be something I am doing wrong or missing here.
private void processContacts() {
Cursor cursor = getContacts();
Log.d(TAG, "Processing " + cursor.getCount() + " contacts");
while(cursor.moveToNext()) {
final long contactId = cursor.getLong(0);
final String name = cursor.getString(1);
if (!TextUtils.isEmpty(name)) {
final Uri contactUri = ContentUris.withAppendedId(
ContactsContract.Contacts.CONTENT_URI,
contactId);
if(ContactsContract.Contacts.openContactPhotoInputStream(getContentResolver(),
contactUri, true) == null) {
Log.d(TAG, String.format("Creating identicon for %s", name));
generateIdenticon(contactId, name);
} else {
Log.i(TAG, String.format("%s already has a contact photo", name));
}
}
}
cursor.close();
}
private Cursor getContacts() {
Uri uri = ContactsContract.Contacts.CONTENT_URI;
String[] projection = new String[] { ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME };
String sortOrder = ContactsContract.Contacts.DISPLAY_NAME
+ " COLLATE LOCALIZED ASC";
return getContentResolver().query(uri, projection, null, null, sortOrder);
}
private void generateIdenticon(long contactId, String name) {
if (!TextUtils.isEmpty(name)) {
updateNotification(getString(R.string.identicons_creation_service_running_title),
String.format(getString(R.string.identicons_creation_service_contact_summary),
name));
final byte[] hash = Identicon.generateHash(name);
final byte[] identicon = Identicon.generateIdenticonByteArray(hash);
if (identicon == null) {
Log.e(TAG, "generateIdenticon() - identicon for " + name + " is null!");
} else {
if (!setContactPhoto(getContentResolver(), identicon, contactId)) {
Log.e(TAG, "Unable to save identicon for " + name);
}
}
}
}
private boolean setContactPhoto(ContentResolver resolver, byte[] bytes, long personId) {
ContentValues values = new ContentValues();
int photoRow = -1;
String where = ContactsContract.Data.RAW_CONTACT_ID + " == " +
String.valueOf(personId) + " AND " + ContactsContract.Data.MIMETYPE + "=='" +
ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE + "'";
Cursor cursor = resolver.query(
ContactsContract.Data.CONTENT_URI,
null,
where,
null,
null);
int idIdx = cursor.getColumnIndexOrThrow(ContactsContract.Data._ID);
if(cursor.moveToFirst()){
photoRow = cursor.getInt(idIdx);
}
cursor.close();
values.put(ContactsContract.Data.RAW_CONTACT_ID, personId);
values.put(ContactsContract.Data.IS_PRIMARY, 1);
values.put(ContactsContract.Data.IS_SUPER_PRIMARY, 1);
values.put(ContactsContract.CommonDataKinds.Photo.PHOTO, bytes);
values.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE);
if (photoRow >= 0) {
final int rowsUpdated = resolver.update(ContactsContract.Data.CONTENT_URI,
values, ContactsContract.Data._ID + "=" + photoRow, null);
return rowsUpdated >= 1;
} else {
final Uri uri = resolver.insert(ContactsContract.Data.CONTENT_URI, values);
return uri != null && !TextUtils.isEmpty(uri.toString());
}
}
All this is being done inside a background service and all my contacts are synced via google. One last thing to note is that these select contacts always return null when I call ContactsContract.Contacts.openContactPhotoInputStream() to see if a photo is available (even after I've attempted to update the photo).
Any help or insight about what may be going on is greatly appreciated.
The following function has a phone number as input parameter (e.g. +436641234567 or +436641234567) and performs two lookups in the Contacts database: first, identify the user belonging to this number (this already works) and then to use the id of the user to get all groups this contact is assigned to (and this does not work). Test gives back the correct id (again), however, the group is "null".
public String getNameGroupByNumber(Context context, String number) {
String name = "?";
String contactId = "0";
String group = "0";
String test = "0";
// Step 1: LookUp Name to given Number
ContentResolver contentResolver = context.getContentResolver();
Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(number));
String[] contactProjection = new String[] {BaseColumns._ID, ContactsContract.PhoneLookup.DISPLAY_NAME };
Cursor contactLookup = contentResolver.query(uri, contactProjection, null, null, null);
try {
if (contactLookup != null && contactLookup.getCount() > 0) {
contactLookup.moveToNext();
name = contactLookup.getString(contactLookup.getColumnIndex(ContactsContract.Data.DISPLAY_NAME));
contactId = contactLookup.getString(contactLookup.getColumnIndex(BaseColumns._ID));
}
} finally {
if (contactLookup != null) {
contactLookup.close();
}
}
Log.d(TAG, "Name: " +name + " ContactId: " + contactId); // works as expected
// Step 2: Lookup group memberships of the contact found in step one
Uri groupURI = ContactsContract.Data.CONTENT_URI;
String[] groupProjection = new String[]{ ContactsContract.CommonDataKinds.GroupMembership.GROUP_ROW_ID , ContactsContract.CommonDataKinds.GroupMembership.CONTACT_ID};
Cursor groupLookup = contentResolver.query(groupURI, groupProjection, ContactsContract.CommonDataKinds.GroupMembership.CONTACT_ID+"="+contactId, null, null);
try {
if (groupLookup != null && groupLookup.getCount() > 0) {
groupLookup.moveToNext();
test = groupLookup.getString(groupLookup.getColumnIndex(ContactsContract.CommonDataKinds.GroupMembership.CONTACT_ID));
group = groupLookup.getString(groupLookup.getColumnIndex(ContactsContract.CommonDataKinds.GroupMembership.GROUP_ROW_ID));
Log.d(TAG, "Group found with Id: " + test + " and GroupId: " + group); // test is again the contactID from above but group is null
}
} finally {
if (groupLookup != null) {
groupLookup.close();
}
}
return name;
}
Cursor groupLookup = getContentResolver().query(
ContactsContract.Data.CONTENT_URI,
new String[]{
ContactsContract.CommonDataKinds.GroupMembership.GROUP_ROW_ID ,
ContactsContract.CommonDataKinds.GroupMembership.CONTACT_ID
},
ContactsContract.Data.MIMETYPE + "=? AND " + ContactContract.Data.CONTACT_ID + "=?",
new String[]{
ContactsContract.CommonDataKinds.GroupMembership.CONTENT_ITEM_TYPE,
contact_id
}, null
);
Use this groupLookup cursor instead.
Cursor groupCursor = getContentResolver().query(
ContactsContract.Groups.CONTENT_URI,
new String[]{
ContactsContract.Groups._ID,
ContactsContract.Groups.TITLE
}, ContactsContract.Groups._ID + "=" + _id, null, null
);
groupCursor helps to get Group title from _id.
Hy everybody.
I need to get the email contact that I have in android by id of contact. But it returns a null value. Don't return nothing and i don't know where I'm failed.
public Cursor cursorEmailByContactId(long contactId) {
Uri uri = ContactsContract.CommonDataKinds.Email.CONTENT_URI;
String[] projection = new String[] {
ContactsContract.CommonDataKinds.Email.DATA,
ContactsContract.CommonDataKinds.Email.TYPE,
ContactsContract.CommonDataKinds.Email.LABEL,
};
String where = ContactsContract.CommonDataKinds.Email.CONTACT_ID
+ " = ? ";
String[] whereParams = new String[] { String.valueOf(contactId) };
String order = ContactsContract.CommonDataKinds.Email.IS_PRIMARY
+ " DESC, " + ContactsContract.CommonDataKinds.Email.DATA
+ " COLLATE LOCALIZED ASC";
return ctx.getContentResolver().query(uri, projection, where,
whereParams, order);
}
Cursor cursorEmail = null;
cursorEmail = sds.cursorEmailByContactId(idContacto);
correioElectr = (EditText)findViewById(R.id.sfe_etEmail);
try{
if(cursorEmail.moveToFirst())
do{
sEmail = cursorEmail.getString(cursorEmail.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
}while(cursorEmail.moveToNext());
}finally{
if(cursorEmail != null && !cursorEmail.isClosed())
cursorEmail.close();
}
correioElectr.setText(sEmail);
And i don't get nothing in the correioElectr editText.
Someone can help me?
Thanks
try with XMPP like this
https://stackoverflow.com/questions/9885154/how-to-get-images-from-xmpp-in-android-application/10272947#10272947