Changing contact's picture on android? - 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"/>

Related

Contact fetching takes too much time

In my code the contact fetching takes too much time to fetch the contacts and show in the application.
Please guide me where i am wrong and what should i correct in order to make execution time fast.
Here is my code.
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null,
null, null, null );
String phone = null;
List<String> phonenumber = new ArrayList<String>();
String emailContact = null;
String emailType = null;
String image_uri = "";
Bitmap bitmap = 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));
image_uri = cur
.getString(cur
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.PHOTO_URI));
if (Integer
.parseInt(cur.getString(cur
.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0)
{
System.out.println("name : " + name + ", ID : " + id);
Cursor pCur = cr.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID
+ " = ?", new String[]{id}, null);
Log.e("pCur","dfgfdg "+pCur.getCount());
while (pCur.moveToNext())
{
phone = pCur
.getString(pCur
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
// contactid=pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
/* phonenumber.add(pCur
.getString(pCur
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)));`*/
Log.e("phone" ,phone);
}
pCur.close();
Cursor emailCur = cr.query
(
ContactsContract.CommonDataKinds.Email.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Email.CONTACT_ID
+ " = ?", new String[]{id}, null);
while (emailCur.moveToNext())
{
emailContact = emailCur
.getString(emailCur
.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
if(TextUtils.isEmpty(emailContact)||emailContact.equalsIgnoreCase(null)||emailContact.equalsIgnoreCase(""))
{
emailContact="";
Log.e("isEmpty","isEmpty " + emailContact);
}
else
{
Log.e("gfdszfg","Email " + emailContact);
}
/* emailType = emailCur
.getString(emailCur
.getColumnIndex(ContactsContract.CommonDataKinds.Email.TYPE));*/
Log.e("gfdszfg","Email " + emailContact);
}
emailCur.close();
}
if (image_uri != null)
{
System.out.println(Uri.parse(image_uri));
try
{
bitmap = MediaStore.Images.Media
.getBitmap(this.getContentResolver(),
Uri.parse(image_uri));
System.out.println(bitmap);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
mList.add(new Contacts(name, phone, image_uri,emailContact));
emailContact="";
}
cur.close();
mMyContactsAdapter = new MyContactsAdapter(MainActivity.this, mList);
mcontact.setAdapter(mMyContactsAdapter);
}
and more over in my code my contact fetching while loop is looping 3 times i dont know why.
I have faced this situation as you are in right now. Try below code
public static ArrayList ReadContactsSpecialWay(Context context) {
StringBuffer contactBuffer = new StringBuffer();
StringBuffer emailBuffer = new StringBuffer();
ArrayList<String> contactList = new ArrayList<>();
ArrayList<String> emailList = new ArrayList<>();
ArrayList<ContactModel> contactModelsList = new ArrayList<>();
HashMap<Integer, Boolean> hashMap = new HashMap<Integer, Boolean>();
String[] emailsAndContacts = new String[2];
// Phone numbers
Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
String[] projection = new String[]{
ContactsContract.CommonDataKinds.Phone.CONTACT_ID,
ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.NUMBER
};
Cursor phoneNumbers = context.getContentResolver().query(uri, projection, null, null, null);
int indexContactID = phoneNumbers.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID);
int indexName = phoneNumbers.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
int indexNumber = phoneNumbers.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
while (phoneNumbers.moveToNext()) {
Integer contactId = phoneNumbers.getInt(indexContactID);
String contactName = phoneNumbers.getString(indexName);
String contactNumber = phoneNumbers.getString(indexNumber).replace(" ", "");
ContactModel contactModel = new ContactModel();
contactModel.setContactPhone(contactNumber);
contactNumber = contactModel.getContactPhone();
if (hashMap.containsKey(contactId))
contactModel.setContactName(contactName + " (" + contactNumber + ")");
else {
hashMap.put(contactId, true);
contactModel.setContactName(contactName);
}
contactModelsList.add(contactModel);
contactList.add(contactNumber);
LogHelper.informationLog(contactNumber + " " + contactName);
contactBuffer.append(contactNumber + ",");
}
phoneNumbers.close();
// Emails
uri = ContactsContract.CommonDataKinds.Email.CONTENT_URI;
projection = new String[]{
ContactsContract.CommonDataKinds.Email.CONTACT_ID,
ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Email.DATA
};
Cursor emails = context.getContentResolver().query(uri, projection, null, null, null);
indexContactID = emails.getColumnIndex(ContactsContract.CommonDataKinds.Email.CONTACT_ID);
indexName = emails.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
int indexData = emails.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA);
while (emails.moveToNext()) {
Integer contactId = emails.getInt(indexContactID);
String contactName = emails.getString(indexName);
String contactEmail = emails.getString(indexData).toLowerCase();
ContactModel contactModel = new ContactModel();
contactModel.setEmailAddress(contactEmail);
if (hashMap.containsKey(contactId)) {
contactModel.setEmailName(contactName + " (" + contactEmail + ")");
} else {
contactModel.setEmailName(contactName);
hashMap.put(contactId, true);
}
contactModelsList.add(contactModel);
if (contactEmail != null && !emailList.contains(contactEmail)) {
emailList.add(contactEmail);
LogHelper.informationLog(contactEmail + " " + contactName);
emailBuffer.append(contactEmail + ",");
}
}
emails.close();
if (contactBuffer.toString().length() > 0) {
emailsAndContacts[0] = contactBuffer.toString().substring(0, (contactBuffer.toString().length() - 1));
} else
emailsAndContacts[0] = "";
if (emailBuffer.toString().length() > 0) {
emailsAndContacts[1] = emailBuffer.toString();
} else {
emailsAndContacts[1] = "";
}
if(contactModelsList.size() == 0)
return null;
else {
ArrayList specialList = new ArrayList();
specialList.add(contactModelsList);
specialList.add(emailsAndContacts);
return specialList;
}
}
It will definitely help you out.
Try this, using AsyncTask. Use it while launching apps default activity on background and fetch the array while using on another activity
class LoadContact extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... voids) {
// Get Contact list from Phone
Uri CONTENT_URI = ContactsContract.Contacts.CONTENT_URI;
String _ID = ContactsContract.Contacts._ID;
String DISPLAY_NAME = ContactsContract.Contacts.DISPLAY_NAME;
Uri PhoneCONTENT_URI = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
String Phone_CONTACT_ID = ContactsContract.CommonDataKinds.Phone.CONTACT_ID;
String NUMBER = ContactsContract.CommonDataKinds.Phone.NUMBER;
ContentResolver contentResolver = getContentResolver();
/**
* #discussion Query contact and return name and contact Id.
*/
Cursor cursor = contentResolver.query(CONTENT_URI, null, null, null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC");
if (cursor.getCount() > 0) {
while (cursor.moveToNext()) {
Bitmap bit_thumb = null;
String contact_id = cursor.getString(cursor.getColumnIndex(_ID));
String name = cursor.getString(cursor.getColumnIndex(DISPLAY_NAME));
String image_thumb = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.PHOTO_THUMBNAIL_URI));
Cursor phoneCursor = contentResolver.query(PhoneCONTENT_URI, null, Phone_CONTACT_ID + " = ?", new String[]{contact_id}, null);
try {
if (image_thumb != null) {
bit_thumb = MediaStore.Images.Media.getBitmap(contentResolver, Uri.parse(image_thumb));
}
} catch (IOException e) {
e.printStackTrace();
}
while (phoneCursor.moveToNext()) {
String phoneNumber = phoneCursor.getString(phoneCursor.getColumnIndex(NUMBER));
final SelectUser selectUser = new SelectUser();
selectUser.setName(name);
selectUser.setContactId(contact_id + "" + phoneNumber);
selectUser.setThumb(bit_thumb);
selectUser.setPhone(phoneNumber);
if (selectUser.getPhone() != null && selectUser.getPhone().length() > 0 && !num.equalsIgnoreCase(phoneNumber)) {
num = phoneNumber;
selectUsers.add(selectUser);
}
}
phoneCursor.close();
Cursor cur1 = contentResolver.query(
ContactsContract.CommonDataKinds.Email.CONTENT_URI, null,
ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?",
new String[]{contact_id}, null);
while (cur1.moveToNext()) {
String email = cur1.getString(cur1.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
final SelectUser selectUser = new SelectUser();
selectUser.setName(name);
selectUser.setContactId(contact_id + "" + email);
selectUser.setThumb(bit_thumb);
selectUser.setEmail(email);
if (selectUser.getEmail() != null && selectUser.getEmail().length() > 0 && !userEmail.equalsIgnoreCase(email)) {
userEmail=email;
selectUsers.add(selectUser);
}
}
cur1.close();
}
}
cursor.close();
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
isContactLoaded = true;
}
}

Updating/Setting own user profile image

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

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.

To set Contact Picture using Contact ID

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

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

Categories

Resources