I'm building an app where when a image is clicked the user sees the contacts list and picks one. After clicking on it, it's contact picture should change to the image clicked in the first place.
Here's how i implement it:
....
Intent intent = new Intent(Intent.ACTION_PICK, People.CONTENT_URI);
startActivityForResult(intent, SELECT_CONTACT);
.....
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_CONTACT) {
Uri contactData = data.getData();
????? what should come here???
}
}
}
My question is how do i acces and change the contact picture?
Thank you
First, get the Uri for the Contacts first raw contact:
Uri rawContactUri = null;
Cursor rawContactCursor = managedQuery(
RawContacts.CONTENT_URI,
new String[] {RawContacts._ID},
RawContacts.CONTACT_ID + " = " + contactData.getLastPathSegment(),
null,
null);
if(!rawContactCursor.isAfterLast()) {
rawContactCursor.moveToFirst();
rawContactUri = RawContacts.CONTENT_URI.buildUpon().appendPath(""+rawContactCursor.getLong(0)).build();
}
rawContactCursor.close();
Then, convert a bitmap to a byte array:
Bitmap bit; // <-- put your bitmap here
ByteArrayOutputStream streamy = new ByteArrayOutputStream();
bit.compress(CompressFormat.PNG, 0, streamy);
byte[] photo = streamy.toByteArray();
Finally, set the byte array as the raw contact's photo:
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);
}
}
EDIT
Be sure to include these two permissions in your manifest:
<uses-permission android:name="android.permission.WRITE_CONTACTS"/>
<uses-permission android:name="android.permission.READ_CONTACTS"/>
Related
I'm trying to Read Phone number of a Contact Selected using Contact Picker.
The Display Name works fine, But Phone number doesn't.
Code:
//calling Contact Picker
public void CPick(View v){
Intent intent=new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(intent, PICK_CONTACT);
}
#Override
//Contact Picker here:
protected void onActivityResult(int reqCode, int resultCode, Intent data){
super.onActivityResult(reqCode,resultCode, data);
if (reqCode==PICK_CONTACT){
if(resultCode==AppCompatActivity.RESULT_OK){
Uri contatctData=data.getData();
Cursor c=getContentResolver().query(contatctData,null,null,null,null);
if (c.moveToFirst()){
//String name=c.getString(c.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME));
//Above line works Fine
String name=c.getString(c.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.NUMBER));
//Above line gives error on runtime "invalid column"
Toast.makeText(this,"U have picked:"+name,Toast.LENGTH_SHORT).show();
}
}
}
}
Anyhelp will be very Appreciated because I couldn't find relevant answer anywhere.
If you want to allow the user to pick a phone-number, the best option is to use a PHONE-PICKER not a CONTACT-PICKER:
Intent intent = new Intent(Intent.ACTION_PICK, CommonDataKinds.Phone.CONTENT_URI);
startActivityForResult(intent, PICK_PHONE);
...
protected void onActivityResult(int requestCode, int resultCode, Intent intent){
if (requestCode == PICK_PHONE && resultCode == RESULT_OK){
Uri phoneUri = intent.getData();
Cursor cur = getContentResolver().query(phoneUri, new String[] { Phone.DISPLAY_NAME, Phone.NUMBER }, null, null, null);
if (cur != null && cur.moveToFirst()){
String name = cur.getString(0);
String number = cur.getString(1);
Log.d("PHONE-PICKER", "User picker: " + name + " - " + number);
cur.close();
}
}
}
Try this method:
private void retrieveContactNumber() {
String contactNumber = null;
// getting contacts ID
Cursor cursorID = getContentResolver().query(uriContact,
new String[]{ContactsContract.Contacts._ID},
null, null, null);
if (cursorID.moveToFirst()) {
contactId = cursorID.getString(cursorID.getColumnIndex(ContactsContract.Contacts._ID));
}
cursorID.close();
Log.d(TAG, "Contact ID: " + contactId);
// Using the contact ID now we will get contact phone number
Cursor cursorPhone = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
new String[]{ContactsContract.CommonDataKinds.Phone.NUMBER},
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ? AND " +
ContactsContract.CommonDataKinds.Phone.TYPE + " = " +
ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE,
new String[]{contactId}, null);
if (cursorPhone.moveToFirst()) {
contactNumber = cursorPhone.getString(cursorPhone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
}
cursorPhone.close();
Log.d(TAG, "Contact Phone Number: " + contactNumber);
}
You should see the contact number in your logcat.
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 am calling intent to pick a contact using this code.
Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
((Activity) mContext).startActivityForResult(intent, PICK_CONTACT);
#Override
public void onActivityResult(int reqCode, int resultCode, Intent data) {
super.onActivityResult(reqCode, resultCode, data);
if (reqCode == PICK_CONTACT) {
if (resultCode == Activity.RESULT_OK) {
Uri uri= data.getData();
}
Here I want to fetch three information of contact such as Name, Phone number, and contact Image.
I am able to fetch name and number but not able to fetch Image. any help would be appreciated.
use following function:
private String retrieveContactPhoto(String contactID) {
// Bitmap photo = null;
/*
* if (inputStream != null) { photo =
* BitmapFactory.decodeStream(inputStream); ImageView imageView =
* (ImageView) findViewById(R.id.img_contact);
* imageView.setImageBitmap(photo); }
*/
Uri photoUri = ContentUris.withAppendedId(
ContactsContract.Contacts.CONTENT_URI,
Long.parseLong(contactID));
final Cursor image = getContentResolver().query(photoUri,
PHOTO_ID_PROJECTION, null, null,
ContactsContract.Contacts._ID + " ASC");
try {
Integer thumbnailId = null;
if (image.moveToFirst()) {
thumbnailId = image.getInt(image
.getColumnIndex(ContactsContract.Contacts.PHOTO_ID));
Uri uri = ContentUris.withAppendedId(
ContactsContract.Data.CONTENT_URI, thumbnailId);
image.close();
if (uri.toString().equals("content://com.android.contacts/data/0"))
return null;
return uri.toString();
}
} finally {
image.close();
}
return null;
and for showing image use following code
if (entries.get(position).getphoto() != null
&& entries.get(position).getphoto() != "content:////com.android.contacts//data//0") {
try {
holder.photo.setImageURI(Uri.parse(entries.get(position)
.getphoto()));
} catch (Exception e) {
holder.photo.setImageResource(R.drawable.abc); //use default image
}
} else
holder.photo.setImageResource(R.drawable.abc); //use default image
Try following
InputStream photo_stream = ContactsContract.Contacts.openContactPhotoInputStream(getContentResolver(),uri);
BufferedInputStream buf =new BufferedInputStream(photo_stream);
Bitmap my_btmp = BitmapFactory.decodeStream(buf);
Use this:
InputStream input = ContactsContract.Contacts.openContactPhotoInputStream(this.getContentResolver(), uri);
BufferedInputStream buffer =new BufferedInputStream(input);
Bitmap bitmap = BitmapFactory.decodeStream(buffer);
Check the below code which will help you to get the Contact Name,Number and contact Image as well. Call the below code on click of a button.
public void onClickSelectContact(View btnSelectContact) {
// using native contacts selection
// Intent.ACTION_PICK = Pick an item from the data, returning what was selected.
startActivityForResult(new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI), REQUEST_CODE_PICK_CONTACTS);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE_PICK_CONTACTS && resultCode == RESULT_OK) {
Log.d(TAG, "Response: " + data.toString());
uriContact = data.getData();
retrieveContactName();
retrieveContactNumber();
retrieveContactPhoto();
}
}
//To get the Contact Image
private void retrieveContactPhoto() {
Bitmap photo = null;
try {
InputStream inputStream = ContactsContract.Contacts.openContactPhotoInputStream(getContentResolver(),
ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, new Long(contactID)));
if (inputStream != null) {
photo = BitmapFactory.decodeStream(inputStream);
ImageView imageView = (ImageView) findViewById(R.id.img_contact);
imageView.setImageBitmap(photo);
}
assert inputStream != null;
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
//To get Contact Number.
private void retrieveContactNumber() {
String contactNumber = null;
// getting contacts ID
Cursor cursorID = getContentResolver().query(uriContact,
new String[]{ContactsContract.Contacts._ID},
null, null, null);
if (cursorID.moveToFirst()) {
contactID = cursorID.getString(cursorID.getColumnIndex(ContactsContract.Contacts._ID));
}
cursorID.close();
Log.d(TAG, "Contact ID: " + contactID);
// Using the contact ID now we will get contact phone number
Cursor cursorPhone = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
new String[]{ContactsContract.CommonDataKinds.Phone.NUMBER},
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ? AND " +
ContactsContract.CommonDataKinds.Phone.TYPE + " = " +
ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE,
new String[]{contactID},
null);
if (cursorPhone.moveToFirst()) {
contactNumber = cursorPhone.getString(cursorPhone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
}
cursorPhone.close();
Log.d(TAG, "Contact Phone Number: " + contactNumber);
}
//To get Contact Name.
private void retrieveContactName() {
String contactName = null;
// querying contact data store
Cursor cursor = getContentResolver().query(uriContact, null, null, null, null);
if (cursor.moveToFirst()) {
// DISPLAY_NAME = The display name for the contact.
// HAS_PHONE_NUMBER = An indicator of whether this contact has at least one phone number.
contactName = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
}
cursor.close();
Log.d(TAG, "Contact Name: " + contactName);
}
}
Also to get all the phone numbers + email address try as below:
ContentResolver contactResolver = context.getContentResolver();
Cursor cursor = contactResolver.query(Uri.parse(aContact.getLookupUri()), null, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
String displayName = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
String photoUri = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.PHOTO_THUMBNAIL_URI));
String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
String lookupKey = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));
if (Integer.parseInt(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0)
{
Cursor pCur = contactResolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[] { contactId }, null);
while (pCur.moveToNext())
{
String phone = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
String type = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE));
String s = (String) ContactsContract.CommonDataKinds.Phone.getTypeLabel(context.getResources(), Integer.parseInt(type), "");
Log.d("TAG", s + " phone: " + phone);
}
pCur.close();
}
Cursor emailCursor = contactResolver.query(ContactsContract.CommonDataKinds.Email.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?", new String[] { contactId }, null);
while (emailCursor.moveToNext())
{
String phone = emailCursor.getString(emailCursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
int type = emailCursor.getInt(emailCursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.TYPE));
String s = (String) ContactsContract.CommonDataKinds.Email.getTypeLabel(context.getResources(), type, "");
Log.d("TAG", s + " email: " + phone);
}
emailCursor.close();
cursor.close();
}
I have a Bitmap and a Contact id. I want a function that takes these parameters and sets the Bitmap as the Contact picture of that id. Can you help me please?
try
Convert your bitmap into byteArray
Bitmap bit; // <-- put your bitmap here
ByteArrayOutputStream streamy = new ByteArrayOutputStream();
bit.compress(CompressFormat.PNG, 0, streamy);
byte[] photo = streamy.toByteArray();
and then
ContentValues values = new ContentValues();
int photoRow = -1;
String where = ContactsContract.Data.RAW_CONTACT_ID + " == " +
ContentUris.parseId(yourContectID) + " 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(yourContectID));
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);
}
}
don not forget to add permissions WRITE_CONTACTS and READ_CONTACTS in your manifest file
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"/>