Updating/Setting own user profile image - android

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

Related

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

Contact photo not updating for a select few

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.

Get Contact SMS count and contact call time

is there any way to get contact sms counts and contact call time , does android store them anyway ?
I think there are some content that stores sms information , but I do not want to read all of the table to know how much sms send for specific user , do you know other way?
may be helpful for you.
void ReadContacts(String sort) {
String[] fields;
final Uri uri = ContactsContract.Contacts.CONTENT_URI;
final String[] projection = new String[] {
ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.Contacts.PHOTO_URI
};
//boolean mShowInvisible = false;
String selection = ContactsContract.Contacts.IN_VISIBLE_GROUP + " = '1'";
String[] selectionArgs = null;
final String sortOrder = ContactsContract.Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC";
m_curContacts = cr.query(uri, projection, selection, selectionArgs, sortOrder);
String image = ContactsContract.Contacts.PHOTO_URI;
if(image!=null){
fields = new String[] {ContactsContract.Data.DISPLAY_NAME, ContactsContract.Contacts.PHOTO_URI};
}else{
fields = new String[] {ContactsContract.Data.DISPLAY_NAME, user_photo};
}
myadapter= new MySimpleCursorAdapter(this, R.layout.list_search, m_curContacts, fields, new int []{R.id.textView1,R.id.imageView1});
myadapter.setFilterQueryProvider(new FilterQueryProvider() {
public Cursor runQuery(CharSequence constraint) {
String selection;
Log.d("hii", "runQuery constraint:"+constraint);
if(constraint.equals("")){
selection = ContactsContract.Contacts.IN_VISIBLE_GROUP + " = '1'" +
" AND "+ ContactsContract.Contacts.DISPLAY_NAME + " LIKE '%"+"&%#"+"%'";
}else{
selection = ContactsContract.Contacts.IN_VISIBLE_GROUP + " = '1'" +
" AND "+ ContactsContract.Contacts.DISPLAY_NAME + " LIKE '%"+constraint+"%'";
}
String[] selectionArgs = null;//new String[]{"'1'"};//, };
Cursor filter = cr.query(uri, projection, selection, selectionArgs, sortOrder);
return filter;
}
});
/*if you want to see all contact and then search*/
// listview.setAdapter(myadapter);
listview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,long arg3) {
long _id=0;
Cursor c = (Cursor) listview.getItemAtPosition(position);
String DisplayName = c.getString(c.getColumnIndexOrThrow( ContactsContract.Contacts.DISPLAY_NAME));
String id = c.getString(c.getColumnIndex(ContactsContract.Contacts._ID));
c.close();
// get the phone number
Cursor pCur = getApplicationContext().getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,ContactsContract.CommonDataKinds.Phone.CONTACT_ID
+ " = ?", new String[] { id }, null);
while (pCur.moveToNext()) {
number = pCur.getString(pCur .getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
}
pCur.close();
// get email and type
Cursor emailCur = getApplicationContext().getContentResolver().query( ContactsContract.CommonDataKinds.Email.CONTENT_URI, null, ContactsContract.CommonDataKinds.Email.CONTACT_ID
+ " = ?", new String[] { id }, null);
while (emailCur.moveToNext()) {
email = emailCur.getString(emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
String emailType = emailCur.getString(emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.TYPE));
}
emailCur.close();
//getting image from contact
_id = Long.parseLong(id);
String _image=retrieveContactPhoto(_id);
retriveCallLog(number);
number= number.replaceAll( "[^\\d]", "");
int _call=in_call+out_call;
int _sms=in_sms+out_sms;
System.out.println(DisplayName+number+_call+_sms+email);
Intent search = new Intent(getApplicationContext(),Search_Add.class);
search.putExtra("_id", id);
search.putExtra("name", DisplayName);
search.putExtra("number", number.toString());
search.putExtra("image", _image);
search.putExtra("call", Integer.toString(_call));
search.putExtra("sms", Integer.toString(_sms));
search.putExtra("email", email);
startActivity(search);
overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
Toast.makeText(getApplicationContext(), "Selected Person:"+DisplayName,Toast.LENGTH_SHORT).show();
}
public String retrieveContactPhoto(long _id) {
Bitmap photo = null;
ImageView imageView = (ImageView) findViewById(R.id.Image_user);
try {
inputStream = ContactsContract.Contacts.openContactPhotoInputStream(getContentResolver(),
ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, new Long(_id)));
if (inputStream != null) {
photo = BitmapFactory.decodeStream(inputStream);
ByteArrayOutputStream baos=new ByteArrayOutputStream();
photo.compress(Bitmap.CompressFormat.PNG,100, baos);
byte [] b=baos.toByteArray();
user_photo=Base64.encodeToString(b, Base64.DEFAULT);
inputStream.close();
}else {
System.out.println("input stream is null");
BitmapDrawable bmd1 = (BitmapDrawable) getResources().getDrawable(R.drawable.user_pic);
Bitmap bm1 = bmd1.getBitmap();
ByteArrayOutputStream stream1 = new ByteArrayOutputStream();
bm1.compress(Bitmap.CompressFormat.JPEG, 100, stream1);
byte[] bitmapdata1 = stream1.toByteArray();
user_photo = Base64.encodeToString(bitmapdata1, 0);
}
} catch (IOException e) {
e.printStackTrace();
}
return user_photo;
}
public void retriveCallLog(String number){
Database myDatabase=new Database(CustomGallary.this);
number= number.replaceAll( "[^\\d]", "");
Cursor cur=myDatabase.getFirstRecordValue(number);
System.out.println("retrive call log()"+cur.getCount());
if(cur.getCount()>0)
if(cur!=null)
{
cur.moveToFirst();
in_call=cur.getInt(cur.getColumnIndex(Database.RECEIVED_CALL));
out_call=cur.getInt(cur.getColumnIndex(Database.DIALED_CALL));
in_sms=cur.getInt(cur.getColumnIndex(Database.RECEIVED_SMS));
out_sms=cur.getInt(cur.getColumnIndex(Database.SENT_SMS));
int totalcall=in_call+out_call;
int totalsms=in_sms+out_sms;
System.out.println("incomincall:"+in_call+"outgoing:"+out_call);
cur.close();
}else{
Toast.makeText(getApplicationContext(), "NO Call and Sms Found", Toast.LENGTH_SHORT).show();
}
myDatabase.close();
}
});
// cur.close();
}

Changing contact's picture on android?

I'm trying to change contact's photo on android, I'm using the code from here:
http://groups.google.com/group/android-developers/msg/7798b51e01c61c1e?
But it doesn't work..
I'm displaying a list of the contacts, and when a user clicks one of the contacts, it's photo supposed to be changed to a photo which is in the resources.
Here's my entire code:
public class ContactFacesActivity extends ListActivity {
ArrayList<Contact> Contacts;
ContentResolver cr;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Contacts = new ArrayList<Contact>();
cr = 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));
String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
if (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
Contacts.add(new Contact(name, id));
}
}
setListAdapter(new ArrayAdapter<Contact>(ContactFacesActivity.this, android.R.layout.simple_list_item_1, Contacts));
}
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
Bitmap temp = ((BitmapDrawable)getResources().getDrawable(R.drawable.house)).getBitmap();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
temp.compress(CompressFormat.JPEG, 90 , bos);
byte[] bitmapdata = bos.toByteArray();
setPhoto(Uri.withAppendedPath( ContactsContract.Contacts.CONTENT_URI, Contacts.get(position).getID()), bitmapdata);
}
public void setPhoto(Uri personUri, byte[] photo) {
ContentValues values = new ContentValues();
int photoRow = -1;
String where = ContactsContract.Data.RAW_CONTACT_ID + " == " +
ContentUris.parseId(personUri) + " AND " + Data.MIMETYPE + "=='" +
ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE + "'";
Cursor cursor = 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,
ContentUris.parseId(personUri));
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){
getContentResolver().update
(ContactsContract.Data.CONTENT_URI, values, ContactsContract.Data._ID
+ " = " + photoRow, null);
} else {
getContentResolver().insert
(ContactsContract.Data.CONTENT_URI, values);
}
}
}
Get ur Uri Contacts :
Uri iContactUri = null;
Cursor iContactCursor = managedQuery(
RawContacts.CONTENT_URI,
new String[] {RawContacts._ID},
RawContacts.CONTACT_ID + " = " + contactData.getLastPathSegment(),
null,
null);
if(!iContactCursor.isAfterLast()) {
iContactCursor.moveToFirst();
iContactUri = RawContacts.CONTENT_URI.buildUpon().appendPath(""+iContactCursor.getLong(0)).build();
}
ContactCursor.close();
then to bitmap
Bitmap bit; // <-- put your bitmap here
ByteArrayOutputStream streamy = new ByteArrayOutputStream();
bit.compress(CompressFormat.PNG, 0, streamy);
byte[] photo = streamy.toByteArray();
Photos
ContentValues values = new ContentValues();
int photoRow = -1;
String where = ContactsContract.Data.RAW_CONTACT_ID + " == " +
ContentUris.parseId(rawContactUri) + " AND " + Data.MIMETYPE + "=='" +
ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE + "'";
Cursor cursor = managedQuery(
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,
ContentUris.parseId(rawContactUri));
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){
this.getContentResolver().update(
ContactsContract.Data.CONTENT_URI,
values,
ContactsContract.Data._ID + " = " + photoRow, null);
} else {
this.getContentResolver().insert(
ContactsContract.Data.CONTENT_URI,
values);
}
}
Manifest
<uses-permission android:name="android.permission.WRITE_CONTACTS"/>
<uses-permission android:name="android.permission.READ_CONTACTS"/>

How do you retrieve an ID from a phone number?

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

Categories

Resources