remove contact from a specific group in android - android

I am making an android app, I want to remove a contact from a specific group not to delete contact just remove from the group, I have group id and contact id, can anyone please tell me the query to do this,
I want to implement something like Delete contact_id=1 from group_id=2

Contacts are linked to groups with ContactsContract.CommonDataKinds.GroupMembership records. You can use something like this to delete contact from group:
private void deleteContactFromGroup(long contactId, long groupId)
{
ContentResolver cr = getContentResolver();
String where = ContactsContract.CommonDataKinds.GroupMembership.GROUP_ROW_ID + "=" + groupId + " AND "
+ ContactsContract.CommonDataKinds.GroupMembership.RAW_CONTACT_ID + "=?" + " AND "
+ ContactsContract.CommonDataKinds.GroupMembership.MIMETYPE + "='"
+ ContactsContract.CommonDataKinds.GroupMembership.CONTENT_ITEM_TYPE + "'";
for (Long id : getRawContactIdsForContact(contactId))
{
try
{
cr.delete(ContactsContract.Data.CONTENT_URI, where,
new String[] { String.valueOf(id) });
} catch (Exception e)
{
e.printStackTrace();
}
}
}
private HashSet<Long> getRawContactIdsForContact(long contactId)
{
HashSet<Long> ids = new HashSet<Long>();
Cursor cursor = getContentResolver().query(RawContacts.CONTENT_URI,
new String[]{RawContacts._ID},
RawContacts.CONTACT_ID + "=?",
new String[]{String.valueOf(contactId)}, null);
if (cursor != null && cursor.moveToFirst())
{
do
{
ids.add(cursor.getLong(0));
} while (cursor.moveToNext());
cursor.close();
}
return ids;
}
Note that when you perform delete, you should specify RAW_CONTACT_ID instead of CONTACT_ID. So you need to query all raw contact ids for specified contact.
Also you may need to consider account data. In that case change querying for contact ids to something like that:
Uri rawContactUri = RawContacts.CONTENT_URI.buildUpon()
.appendQueryParameter(RawContacts.ACCOUNT_NAME, accountName)
.appendQueryParameter(RawContacts.ACCOUNT_TYPE, accountType).build();
Cursor cursor = getContentResolver().query(rawContactUri,
new String[] { RawContacts._ID }, RawContacts.CONTACT_ID + "=?",
new String[] { String.valueOf(contactId) }, null);

public static Uri addContactToGroup(String rawContactId,String groupId)
{
try
{
ContentValues values = new ContentValues();
values.put(Data.RAW_CONTACT_ID, rawContactId);
values.put(GroupMembership.GROUP_ROW_ID, groupId);
values.put(Data.MIMETYPE, GroupMembership.CONTENT_ITEM_TYPE);
return getContentResolver.insert(Data.CONTENT_URI, values);
}
catch (Exception e)
{}
return Uri.EMPTY;
}
//-----------------------------------
public static int removeContactFromGroup(String contactId,String groupId)
{
try
{
String where = Data.CONTACT_ID + " = ? AND " + Data.MIMETYPE + " = ? AND " + GroupMembership.GROUP_ROW_ID + " = ?";
String[] args = {contactId, GroupMembership.CONTENT_ITEM_TYPE, groupId};
return getContentResolver.delete(Data.CONTENT_URI, where, args);
}
catch (Exception e)
{}
return 0;
}

Related

Adding photo tumbnail to existing Android contact without photo

I've created a contact in the Android address book programmatically, which has a name and phone number. Now I'd like to add a photo to this contact, but I can't seem to get this working. I don't receive an error message, but the photo doesn't seem to get added.
If I create a new contact WITH photo, the photo is added correctly, and I can update the exisiting photo of this contact as well. Only problem is a contact without photo.
I've already read several solutions here and here, and tried several variations based on these answers, but neither works. My best guess is that I'm doing something wrong with the RAW_CONTACT_ID. Anyone who can find my bug?
private void createNewContact()
{
ArrayList<ContentProviderOperation> ops = new ArrayList<>();
ContentProviderOperation.Builder builder = ContentProviderOperation.newInsert(RawContacts.CONTENT_URI);
builder.withValue(RawContacts.ACCOUNT_TYPE, MY_ACCOUNT_TYPE);
builder.withValue(RawContacts.ACCOUNT_NAME, MY_ACCOUNT_NAME);
ops.add(builder.build());
builder = ContentProviderOperation.newInsert(Data.CONTENT_URI);
builder.withValueBackReference(Data.RAW_CONTACT_ID, 0);
builder.withValue(Data.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE);
builder.withValue(StructuredName.GIVEN_NAME, myName);
ops.add(builder.build());
builder = ContentProviderOperation.newInsert(Data.CONTENT_URI);
builder.withValueBackReference(Data.RAW_CONTACT_ID, 0);
builder.withValue(Data.MIMETYPE, Phone.CONTENT_ITEM_TYPE);
builder.withValue(Phone.TYPE, Phone.TYPE_WORK);
builder.withValue(Phone.NUMBER, myPhoneNumber);
ops.add(builder.build());
builder = ContentProviderOperation.newInsert(Data.CONTENT_URI);
builder.withValueBackReference(Data.RAW_CONTACT_ID, 0);
builder.withValue(Data.MIMETYPE, Photo.CONTENT_ITEM_TYPE);
builder.withValue(Photo.PHOTO, myPhotoByteArray);
ops.add(builder.build());
try
{
context.getContentResolver().applyBatch(AUTHORITY, ops);
}
catch (Exception e)
{
// Handle exception
}
}
private static final String BASIC_SELECTION = RawContacts.ACCOUNT_TYPE + "='" + MY_ACCOUNT_TYPE + "'";
private void editContact() {
ArrayList<ContentProviderOperation> ops = new ArrayList<>();
ContentProviderOperation.Builder builder = ContentProviderOperation.newUpdate(Data.CONTENT_URI);
builder.withSelection(BASIC_SELECTION + " AND " + Data.MIMETYPE + "='" + StructuredName.CONTENT_ITEM_TYPE + "'", null);
builder.withValue(StructuredName.GIVEN_NAME, myName);
ops.add(builder.build());
builder = ContentProviderOperation.newUpdate(Data.CONTENT_URI);
builder.withSelection(BASIC_SELECTION + " AND " + Data.MIMETYPE + "='" + Phone.CONTENT_ITEM_TYPE + "'" + " AND " + Phone.TYPE + "='" + Phone.TYPE_WORK + "'", null);
builder.withValue(Phone.NUMBER, myPhoneNumber);
ops.add(builder.build());
if (isContactWithoutPhoto())
{
// Contact without photo: insert new photo
// TODO: this part doesn't work yet!
int rawContactId = getRawContactId();
if (rawContactId != -1)
{
builder = ContentProviderOperation.newInsert(Data.CONTENT_URI);
builder.withValue(Data.RAW_CONTACT_ID, rawContactId);
builder.withValue(Data.MIMETYPE, Photo.CONTENT_ITEM_TYPE);
builder.withValue(Photo.PHOTO, myPhotoByteArray);
ops.add(builder.build());
}
}
else
{
// Contact already has a photo: update
builder = ContentProviderOperation.newUpdate(Data.CONTENT_URI);
builder.withSelection(BASIC_SELECTION + " AND " + Data.MIMETYPE + "='" + Photo.CONTENT_ITEM_TYPE + "'", null);
builder.withValue(Photo.PHOTO, myPhotoBytes);
ops.add(builder.build());
}
try
{
context.getContentResolver().applyBatch(AUTHORITY, ops);
}
catch (Exception e)
{
// Handle exception
}
}
private int getRawContactId()
{
int rawContactId = -1;
Cursor cursor = null;
try
{
cursor = App.getContext().getContentResolver().query(RawContacts.CONTENT_URI, null, ACCOUNT_TYPE_SELECTION, null, null);
if (cursor != null && cursor.moveToFirst())
{
rawContactId = cursor.getInt(cursor.getColumnIndex(RawContacts._ID));
}
}
finally
{
if (cursor != null)
{
cursor.close();
}
}
return rawContactId;
}
EDIT:
I only need a single contact, which is created a single time, after which it only needs to be updated regularly. This contact is saved on a self-created account with type MY_ACCOUNT_TYPE & name MY_ACCOUNT_NAME. Hence the builder.withSelection(BASIC_SELECTION for each update operation, which uses MY_ACCOUNT_TYPE rather than an id.
I have also tried to add that same selection on the 'update photo on existing contact' part, to implement it more like the other 'update' code, because I want to be sure I update the photo ONLY for that single contact:
int rawContactId = getRawContactId();
if (rawContactId != -1)
{
builder = ContentProviderOperation.newInsert(Data.CONTENT_URI);
builder.withSelection(BASIC_SELECTION + " AND " + Data.MIMETYPE + "='" + Photo.CONTENT_ITEM_TYPE + "'", null);
builder.withValue(Data.RAW_CONTACT_ID, rawContactId);
builder.withValue(Photo.PHOTO, myPhotoByteArray);
ops.add(builder.build());
In this case the app obviously crashes with the error java.lang.IllegalArgumentException: only updates, deletes, and asserts can have selections. The id is already collected using the BASIC_SELECTION, so I expect the correct contact to be updated in this way anyway.
In case somebody wonders which (static) imports for ContactsContract are used:
import android.provider.ContactsContract.CommonDataKinds.Photo;
import android.provider.ContactsContract.PhoneLookup;
import static android.provider.ContactsContract.AUTHORITY;
import static android.provider.ContactsContract.CommonDataKinds.Note;
import static android.provider.ContactsContract.CommonDataKinds.Phone;
import static android.provider.ContactsContract.CommonDataKinds.StructuredName;
import static android.provider.ContactsContract.Data;
import static android.provider.ContactsContract.RawContacts;
Don't access CommonDataKinds.Photo directly, instead use the APIs supplied helper class DisplayPhoto.
This helper class will populate both PHOTO and PHOTO_FILE_ID which is what your code was missing.
try the following:
public void setPhoto(long rawContactId, byte[] photo) {
Uri rawContactPhotoUri = Uri.withAppendedPath(ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId), RawContacts.DisplayPhoto.CONTENT_DIRECTORY);
try {
AssetFileDescriptor fd = contentResolver.openAssetFileDescriptor(rawContactPhotoUri, "rw");
OutputStream os = fd.createOutputStream();
os.write(photo);
os.close();
fd.close();
} catch (IOException e) {
Log.e(TAG, "error", e);
}
}
With a lot of trial and error I found the RawContactId was not correct.
Finally I came up with this solution: retrieve the RawContacts.CONTACT_ID using PhoneLookup._ID, which can be retrieved by the phoneNumber.
// This code stays the same as described in the question (except for some error handling and closing cursors, which I left out for simplicity sake):
private void createNewContact() {
...
}
private static final String BASIC_SELECTION = RawContacts.ACCOUNT_TYPE + "='" + MY_ACCOUNT_TYPE + "'";
private void editContact() {
...
int rawContactId = getRawContactId();
...
}
// The different part is the way to retrieve the RawContactId:
private static final ContentResolver CONTENT_RESOLVER = context.getContentResolver();
private int getRawContactId()
{
String[] projection = {Phone.NUMBER};
Cursor cursor = CONTENT_RESOLVER.query(Phone.CONTENT_URI, projection, BASIC_SELECTION, null, null);
String phoneNumber = cursor.getString(cursor.getColumnIndex(Phone.NUMBER));
return getRawContactIdWithPhoneNumber(phoneNumber);
}
private int getRawContactIdWithPhoneNumber(String phoneNumber)
{
Uri uri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phoneNumber));
String[] projection = {PhoneLookup._ID, PhoneLookup.DISPLAY_NAME};
Cursor cursor = CONTENT_RESOLVER.query(uri, projection, BASIC_SELECTION, null, null);
int id = cursor.getInt(cursor.getColumnIndex(PhoneLookup._ID));
return getRawContactIdWithPhoneLookupId(id);
}
private int getRawContactIdWithPhoneLookupId(int id)
{
String[] projection = new String[]{RawContacts._ID};
String selection = RawContacts.CONTACT_ID + "=?";
String[] selectionArgs = new String[]{String.valueOf(id)};
Cursor cursor = CONTENT_RESOLVER.query(RawContacts.CONTENT_URI, projection, selection, selectionArgs, null);
return cursor.getInt(cursor.getColumnIndex(RawContacts._ID));
}

Want to create,update and retrieve data from SqLite

For Create table :
private static void createAllTables(SQLiteDatabase database) {
database.execSQL(" CREATE TABLE IF NOT EXISTS " + IN_RIDE_DATA + " (" + USER_ID + " REAL NOT NULL" +"," + TOTAL_DISPLACEMENT_DISTANCE + " REAL NOT NULL" + "" + ");");
}
for Update table, want to save only displacement so i update every time because i want to override the data.
public void insertTotalDisplacement(String userID, Double displacement) {
try {
ContentValues contentValues = new ContentValues();
contentValues.put(NewDatabaseForInRideData.USER_ID, userID); //User phone No used as a USER ID
contentValues.put(NewDatabaseForInRideData.TOTAL_DISPLACEMENT_DISTANCE, displacement);
database.update(NewDatabaseForInRideData.IN_RIDE_DATA,contentValues, NewDatabaseForInRideData.USER_ID+" = "+userID, new String [] {});
} catch (Exception e) {
e.printStackTrace();
}
}
For Retrieving data, I used several ways to do this but data not save in database and not retrieved from database.
public Cursor getTotalDisplacementDistance() {
Cursor cursor=null;
try {
String[] columns = new String[]{NewDatabaseForInRideData.TOTAL_DISPLACEMENT_DISTANCE};
// cursor = database.rawQuery(NewDatabaseForInRideData.IN_RIDE_DATA, columns, null, null, null, null, null);
//choice = String.valueOf(cursor.getDouble(cursor.getColumnIndex(NewDatabaseForInRideData.TOTAL_DISPLACEMENT_DISTANCE)));
Cursor cur=database.rawQuery("SELECT "+NewDatabaseForInRideData.TOTAL_DISPLACEMENT_DISTANCE+" where "+NewDatabaseForInRideData.USER_ID+" = " +1+ " from"+NewDatabaseForInRideData.IN_RIDE_DATA,new String [] {});
//Cursor cur=database.rawQuery("SELECT * from IN_RIDE_DATA",new String [] {});
if (cursor != null) {
cursor.moveToFirst();
}
return cursor;
} catch (Exception e) {
e.printStackTrace();
return cursor;
}
}
The issue is in getTotalDisplacementDistance method, you are using two cursor variables, one has query result and other is null, and you are processing the one with null value.
Update it accordingly,
public Cursor getTotalDisplacementDistance() {
Cursor cursor=null;
try {
cursor = database.rawQuery("SELECT " + NewDatabaseForInRideData.TOTAL_DISPLACEMENT_DISTANCE + " from IN_RIDE_DATA where " + NewDatabaseForInRideData.USER_ID + " = ?", new String[] {"1"});
if (cursor != null) {
cursor.moveToFirst();
}
return cursor;
} catch (Exception e) {
e.printStackTrace();
return cursor;
}
}
You can try this
String selectQuery = "SELECT * FROM " + IN_RIDE_DATA;
SQLiteDatabase db = dbHelper.getWritableDatabase();
db.beginTransaction();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Contact contact = new Contact();
contact.setID(Integer.parseInt(cursor.getString(cursor.getColumnIndex(NewDatabaseForInRideData.USER_ID))));
contact.setName(cursor.getString(cursor.getColumnIndex(NewDatabaseForInRideData.TOTAL_DISPLACEMENT_DISTANCE))));
// Adding data to your list
list.add(contact);
} while (cursor.moveToNext());
db.setTransactionSuccessful();
}
db.endTransaction();
Edit
Use you model class for setting data
I change these things
For Creating Table
private static void createAllTables(SQLiteDatabase database) {
//database.execSQL(" CREATE TABLE IF NOT EXISTS " + IN_RIDE_DATA + " (" + USER_ID +"," + TOTAL_DISPLACEMENT_DISTANCE + "" + ");");
database.execSQL(" CREATE TABLE IF NOT EXISTS " + IN_RIDE_DATA + " ("
+ TOTAL_DISPLACEMENT_DISTANCE + " TEXT, "
+ USER_ID + " TEXT"+");");
}
For Deleting Table
public void deleteDriverLocData() {
try {
database.delete(NewDatabaseForInRideData.IN_RIDE_DATA, null, null);
} catch (Exception e) {
e.printStackTrace();
}
}
For Inserting
public void insertDisplacement(String id, String displacement) {
try {
deleteDriverLocData();
ContentValues contentValues = new ContentValues();
contentValues.put(NewDatabaseForInRideData.USER_ID, id);
contentValues.put(NewDatabaseForInRideData.TOTAL_DISPLACEMENT_DISTANCE, displacement);
database.insert(NewDatabaseForInRideData.IN_RIDE_DATA, null, contentValues);
} catch (Exception e) {
e.printStackTrace();
}
}
For retrieving the values:
public String getDisplacement() {
try {
String[] columns = new String[]{NewDatabaseForInRideData.TOTAL_DISPLACEMENT_DISTANCE};
Cursor cursor = database.query(NewDatabaseForInRideData.IN_RIDE_DATA, columns, null, null, null, null, null);
cursor.moveToFirst();
String totaldisplacement = cursor.getString(cursor.getColumnIndex(NewDatabaseForInRideData.TOTAL_DISPLACEMENT_DISTANCE));
return totaldisplacement;
} catch (Exception e) {
e.printStackTrace();
return "";
}
}

Delete sms from another activity Android

I access all sms using ("content://sms/inbox") in my custom list view currently i am getting address body and _id now i want to delete selected sms from another activity please guide me i am beginner in andorid
this is my Mainactivity but i want to delete seleted sms from another activity
Uri uri = Uri.parse("content://sms/");
ContentResolver contentResolver = getContentResolver();
Cursor cursor = contentResolver.query(uri, null, null, null, null, null);
if(cursor !=null && cursor.moveToFirst()){
do{
// name = getContactName(address);
tid= cursor.getString(cursor.getColumnIndexOrThrow("_id"));
address = cursor.getString(cursor.getColumnIndexOrThrow("address"));
body = cursor.getString(cursor.getColumnIndexOrThrow("body"));
if(name==null) {
list.add(new mybean("" + address, "" + body,""+tid));
}
else{
list.add(new mybean("" + name, "" + body,""+tid));
}
my =new myadapter(this,list);
lv.setAdapter(my);
}while(cursor.moveToNext());
}
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int pos, long l) {
Intent intent =new Intent(MainActivity.this,Main2Activity.class);
intent.putExtra("delete",list.get(pos).getDel());
intent.putExtra("sms",list.get(pos).getNumber());
intent.putExtra("smsmsg",list.get(pos).getMsg());
startActivity(intent);
}
});
Here is the quide to how to delete sms
Deleting Android SMS programmatically
For kitkat
https://android-developers.googleblog.com/2013/10/getting-your-sms-apps-ready-for-kitkat.html
First you should choose your app as default sms app then you can delete or remove sms from there..
You can also refer to this post
How to delete an SMS from the inbox in Android programmatically?
here is the tutorial for deleting sms programmatically
http://wisdomitsol.com/blog/android/sms/programmatically-delete-sms-in-android
i hope you find these post helpful if any problem you can comment here.
1.First Add permission in manifest
2. write the method
public boolean deleteSms(String smsId) {
boolean isSmsDeleted = false;
try {
mActivity.getContentResolver().delete(
Uri.parse("content://sms/" + smsId), null, null);
isSmsDeleted = true;
} catch (Exception ex) {
isSmsDeleted = false;
}
return isSmsDeleted;
}
you can now delete sms byIds
You can also try this code
try {
Uri uriSms = Uri.parse("content://sms/inbox");
Cursor c = context.getContentResolver().query(
uriSms,
new String[] { "_id", "thread_id", "address", "person",
"date", "body" }, "read=0", null, null);
if (c != null && c.moveToFirst()) {
do {
long id = c.getLong(0);
long threadId = c.getLong(1);
String address = c.getString(2);
String body = c.getString(5);
String date = c.getString(3);
Log.e("log>>>",
"0--->" + c.getString(0) + "1---->" + c.getString(1)
+ "2---->" + c.getString(2) + "3--->"
+ c.getString(3) + "4----->" + c.getString(4)
+ "5---->" + c.getString(5));
Log.e("log>>>", "date" + c.getString(0));
ContentValues values = new ContentValues();
values.put("read", true);
getContentResolver().update(Uri.parse("content://sms/"),
values, "_id=" + id, null);
if (message.equals(body) && address.equals(number)) {
// mLogger.logInfo("Deleting SMS with id: " + threadId);
context.getContentResolver().delete(
Uri.parse("content://sms/" + id), "date=?",
new String[] { c.getString(4) });
Log.e("log>>>", "Delete success.........");
}
} while (c.moveToNext());
}
} catch (Exception e) {
Log.e("log>>>", e.toString());
}

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.

ContactsContract how to enumerate all available fields?

In my application I need to give user opportinity to see/edit all available fields of ContactsContract.
How should I get/see all available fields - including any custom ones?
First get all of the names of people that exist in your phone:
Cursor phones = getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
null,
null,
ContactsContract.Contacts.DISPLAY_NAME
+ " COLLATE LOCALIZED ASC");
while (phones.moveToNext()) {
name = phones
.getString(phones
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
namelist.add(name);
String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
number_list.add(phoneNumber);
detaillist.put(name, phoneNumber);
}
phones.close();
}
Now get contact id and get other information like phone number, email id, address, organization by using contact id:
protected void get_UserContactId(String item_clicked)
{
System.out.println("i m in fincution contact id");
ContentResolver localContentResolver = this.getContentResolver();
Cursor contactLookupCursor =
localContentResolver.query(
Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI,
Uri.encode(item_clicked)),
new String[] {PhoneLookup.DISPLAY_NAME, PhoneLookup._ID},
null,
null,
null);
try {
while(contactLookupCursor.moveToNext()){
contactName = contactLookupCursor.getString(contactLookupCursor.getColumnIndexOrThrow(PhoneLookup.DISPLAY_NAME));
user_contact_id = contactLookupCursor.getString(contactLookupCursor.getColumnIndexOrThrow(PhoneLookup._ID));
System.out.println("contatc id id"+user_contact_id);
}
}
finally {
contactLookupCursor.close();
}
}
protected void get_UserEmail(String item_clicked)
{
Cursor emails = getContentResolver().query(ContactsContract.CommonDataKinds.Email.CONTENT_URI, null, ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = " + user_contact_id, null, null);
while (emails.moveToNext()) {
// This would allow you get several email addresses
user_email_id = emails.getString(
emails.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
String user_email_type=emails.getString(
emails.getColumnIndex(ContactsContract.CommonDataKinds.Email.TYPE));
System.out.println("the email type"+user_email_type);
System.out.println("email address might be"+emailAddress);
contact_attribute_type.add(EMAIL_TYPE[(Integer.parseInt(user_email_type))-1]);
contact_attribute_value.add(user_email_id);
}
emails.close();
}
protected void get_UserNumber(String item_clicked) {
// TODO Auto-generated method stub
final String[] CONTACTS_SUMMARY_PROJECTION = new String[] {
ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.Contacts.STARRED,
ContactsContract.Contacts.TIMES_CONTACTED,
ContactsContract.Contacts.CONTACT_PRESENCE,
ContactsContract.Contacts.PHOTO_ID,
ContactsContract.Contacts.LOOKUP_KEY,
ContactsContract.Contacts.HAS_PHONE_NUMBER,
};
String select = "(" + ContactsContract.Contacts.DISPLAY_NAME + " == \"" +item_clicked+ "\" )";
Cursor c = this.getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, CONTACTS_SUMMARY_PROJECTION, select, null, ContactsContract.Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC");
this.startManagingCursor(c);
if (c.moveToNext())
{
String id = c.getString(0);
ArrayList<String> phones = new ArrayList<String>();
Cursor pCur = this.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = ?", new String[]{id}, null);
while (pCur.moveToNext())
{
phones.add(pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)));
user_number=pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
String number_type=pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE));
System.out.println("the number type---"+number_type);
System.out.println("user no. in share is"+user_number);
contact_attribute_type.add(PHONE_TYPE[(Integer.parseInt(number_type))-1]);
contact_attribute_value.add(user_number);
// Log.i("", name_to_search+ " has the following phone number "+ pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)));
}
pCur.close();
}
}
protected String get_UserAddress() {
// TODO Auto-generated method stub
try {
System.out.println(" i m in user address");
Cursor address = getContentResolver().query(ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_URI,null, ContactsContract.CommonDataKinds.StructuredPostal.CONTACT_ID + " = " + client_contact_id, null, null);
while (address.moveToNext()) {
// This would allow you get several email addresses
user_home_address = address.getString(
address.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.DATA));
String user_address_type=address.getString(
address.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.TYPE));
System.out.println("the user address type"+user_address_type);
System.out.println(" address might be"+user_home_address);
contact_attribute_type.add(ADDRESS_TYPE[(Integer.parseInt(user_address_type))-1]);
contact_attribute_value.add(user_home_address);
}
address.close();
}
catch(Exception e)
{
System.out.println("this exception due to website"+e);
}
return(user_home_address);
}
protected void get_UserWebsite() {
// TODO Auto-generated method stub
try{
Cursor websiteNameCursor = getContentResolver().query(ContactsContract.Data.CONTENT_URI,new String[] {Website.URL}, ContactsContract.Data.CONTACT_ID + " = " + user_contact_id + " AND ContactsContract.Data.MIMETYPE = '"
+ ContactsContract.CommonDataKinds.Website.CONTENT_ITEM_TYPE
+ "'",null,null);
websiteNameCursor.moveToNext();
user_website=(websiteNameCursor.getString(websiteNameCursor.getColumnIndex(Website.URL)));
System.out.println("this is my website"+(websiteNameCursor.getString(websiteNameCursor.getColumnIndex(Website.URL))));
contact_attribute_type.add("Website");
contact_attribute_value.add(user_website);
}
catch(Exception e)
{
user_website=null;
System.out.println("this website is"+user_website);
System.out.println("this exception in website"+e);
}
}
protected void get_UserOrganization() {
// TODO Auto-generated method stub
try{
Cursor organizationNameCursor = getContentResolver().query(ContactsContract.Data.CONTENT_URI,new String[] {Organization.COMPANY}, ContactsContract.Data.CONTACT_ID + " = " + user_contact_id + " AND ContactsContract.Data.MIMETYPE = '"
+ ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE
+ "'",null,null);
organizationNameCursor.moveToNext();
user_company=organizationNameCursor.getString(organizationNameCursor.getColumnIndex(Organization.COMPANY));
// String user_company_type=organizationNameCursor.getString(organizationNameCursor.getColumnIndex(Organization.TYPE));
// System.out.println("the company type "+user_company_type);
System.out.println("this is my organization"+user_company);
contact_attribute_type.add("Company");
contact_attribute_value.add(user_company);
}
catch(Exception e)
{
user_company=null;
System.out.println("user company name is"+user_company);
System.out.println("this exception in org"+e);
}
}
}
By doing this you can get all the fields of contacts-contract.
This logs the name and value of all columns in all contact rows. Tested on Galaxy S6 with native contacts app. I needed it to find the column name that is used for custom SMS notification sound (sec_custom_alert).
private void enumerateColumns() {
Cursor cursor = getApplicationContext().getContentResolver().query(
ContactsContract.Contacts.CONTENT_URI,
null, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
do {
for(int i=0; i<cursor.getColumnCount();i++)
{
Log.d("myActivity", cursor.getColumnName(i) + " : " + cursor.getString(i));
}
} while (cursor.moveToNext());
cursor.close();
}
}

Categories

Resources