The delete all contacts method that seems to do it's job is:
ContentResolver contentResolver = myActivity.getContentResolver();
Cursor cursor = contentResolver.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
while (cursor.moveToNext()) {
String lookupKey = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));
Uri uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_LOOKUP_URI, lookupKey);
contentResolver.delete(uri, null, null);
}
Is there a way to adjust this to delete RawContacts instead of contacts? Something like this:
ContentResolver contentResolver = myActivity.getContentResolver();
Cursor cursor = contentResolver.query(ContactsContract.RawContacts.CONTENT_URI, null, null, null, null);
while (cursor.moveToNext()) {
contentResolver.delete(ContactsContract.RawContacts.CONTENT_URI, null, null);
}
I'm looking for other ways to delete all contacts. What's the best way to clear all the contact tables (Contacts, Raw Contacts, Data)?
Inside the for loop you call below method,
This is all we need.
To delete Contact with phone number and name given
public static boolean deleteContact(Context ctx, String phone, String name) {
Uri contactUri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phone));
Cursor cur = ctx.getContentResolver().query(contactUri, null, null, null, null);
try {
if (cur.moveToFirst()) {
do {
if (cur.getString(cur.getColumnIndex(PhoneLookup.DISPLAY_NAME)).equalsIgnoreCase(name)) {
String lookupKey = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));
Uri uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_LOOKUP_URI, lookupKey);
ctx.getContentResolver().delete(uri, null, null);
return true;
}
} while (cur.moveToNext());
}
} catch (Exception e) {
System.out.println(e.getStackTrace());
}
return false;
}
And remind to add read/write contact permission
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.WRITE_CONTACTS" />
Related
I am working on a project that creates random contacts but I am having trouble implementing the deletion capability. I have marked each generated contact with a note through
ops.add(ContentProviderOperation
.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(Data.RAW_CONTACT_ID,
rawContactInsertIndex)
.withValue(Data.MIMETYPE, Note.CONTENT_ITEM_TYPE)
.withValue(Note.NOTE, note)
.build());
Now to delete the contacts i need to use something similar to what i have found here
Uri contactUri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI,
Uri.encode(phoneNumber));
Cursor cur = ctx.getContentResolver().query(contactUri, null, null,
null, null);
try {
if (cur.moveToFirst()) {
do {
String lookupKey =
cur.getString(cur.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));
Uri uri = Uri.withAppendedPath(
ContactsContract.Contacts.CONTENT_LOOKUP_URI,
lookupKey);
ctx.getContentResolver().delete(uri, null, null);
} while (cur.moveToNext());
}
} catch (Exception e) {
System.out.println(e.getStackTrace());
}
return false;
}
I believe the only difference between the code above and what I am searching for is that the one above uses a phone number to delete the contact but for my purposes I need to delete by the Note field of the contact.
Fixed my problem..I am too new to java and tried comparing strings using '==' instead of stringObject.equals().
here is a little function to delete contacts based on their string in case anyone needs something like that.
public void deleteContacts(String contactNote){
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
null, null, null, null);
String note;
while (cur.moveToNext()) {
note = "";
try{
String lookupKey = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));
String noteWhere = ContactsContract.Contacts.LOOKUP_KEY + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?";
String[] noteWhereParams = new String[]{lookupKey,
ContactsContract.CommonDataKinds.Note.CONTENT_ITEM_TYPE};
Cursor noteCur = cr.query(ContactsContract.Data.CONTENT_URI, null, noteWhere, noteWhereParams, null);
if (noteCur.moveToFirst()) {
note = noteCur.getString(noteCur.getColumnIndex(ContactsContract.CommonDataKinds.Note.NOTE));
if(note.equals(contactNote)) {
Uri uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_LOOKUP_URI, lookupKey);
cr.delete(uri, null, null);
}
}
noteCur.close();
}
catch(Exception e)
{
System.out.println(e.getStackTrace());
}
}
cur.close();
}
below is my code for delete contact from phone
Uri contactUri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI,
Uri.encode(phone));
Cursor cur = mContext.getContentResolver().query(contactUri, null,
null, null, null);
boolean flag = false;
try {
if (cur.moveToFirst()) {
do {
if (cur.getString(
cur.getColumnIndex(PhoneLookup.DISPLAY_NAME))
.equalsIgnoreCase(name)) {
String lookupKey = cur
.getString(cur
.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));
Uri uri = Uri.withAppendedPath(
ContactsContract.Contacts.CONTENT_LOOKUP_URI,
lookupKey);
mContext.getContentResolver().delete(uri, null, null);
flag=true;
break;
}
} while (cur.moveToNext());
}
} catch (Exception e) {
flag=false;
System.out.println(e.getStackTrace());
}
delete contact from phone is working fine but sim contact delete temporary mean when my phone is restart my contact is recover that i deleted.
help in find solution for this problem.
Thanks...
The URI you want to use is this one : content://icc/adn/
Moreover, you have to use the name and the number to delete a contact.
Try something like this (works for me) :
Uri simUri = Uri.parse("content://icc/adn/");
ContentResolver mContentResolver = this.getContentResolver();
Cursor c = mContentResolver.query(simUri, null, null, null, null);
if (c.moveToFirst())
{
do
{
if (/* your condition here */)
{
mContentResolver.delete(
simUri,
"tag='" + c.getString(c.getColumnIndex("name")) +
"' AND " +
"number='" + c.getString(c.getColumnIndex("number")) + "'"
, null);
break;
}
}
while (c.moveToNext());
}
Off course, don't forget these permissions :
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.WRITE_CONTACTS" />
I'm trying to delete all contacts from a defined group but I don't know how to do a join from the contact table and group table (if it's possible).
ContentResolver cr = getContentResolver();
String where = ContactsContract.Groups.TITLE + " =='LolGroup'";
Cursor cursor = cr.query(
ContactsContract.Contacts.CONTENT_URI, null, where, null, null);
while (cursor.moveToNext()) {
String lookupKey = cursor.getString(
cursor.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));
Uri uri = Uri.withAppendedPath(
ContactsContract.Contacts.CONTENT_LOOKUP_URI, lookupKey);
cr.delete(uri, null, null);
}
Of course it gives me an error because there is no "title" in the contacts group, but if I do a join with the ID I should get what i want.
Any idea how to do that join?
It looks strange because ContactsContract.Contacts does not have ContactsContract.Groups.TITLE column. So I think that you can get group id with the group title you want and then search contacts with the group id. The idea might go like following:
public String getGroupIdByTitle(String groupTitle){
try {
cursor = mContentResolver.query(
ContactsContract.Groups.CONTENT_URI,
new String[] {Groups._ID},
Groups.TITLE + "=?",
new String[]{groupTitle},
null);
while (cursor.moveToNext()){
return cursor.getString(cursor.getColumnIndex(0);
}
} finally {
if (cursor!=null) cursor.close();
}
return "";
}
public String getGroupIdOfContact(String lookupKey) {
String where = String.format("%s=? AND %s=?", Data.LOOKUP_KEY, Data.MIMETYPE);
String[] whereArgs = {lookupKey, GroupMembership.CONTENT_ITEM_TYPE};
String groupRowId = "";
Cursor cursor = mContentResolver.query(
Data.CONTENT_URI,
new String[]{GroupMembership.GROUP_ROW_ID},
where, whereArgs, null);
try {
if (cursor.moveToNext()) {
return cursor.getString(cursor.getColumnIndex(GroupMembership.GROUP_ROW_ID));
}
} finally {
if (cursor!=null) cursor.close();
}
return "";
}
public void deleteContactByGroupTitle(String groupTitle) {
String targetGroupId = getGroupIdByTitle(groupTitle);
Cursor cursor = null;
try {
cursor = mContentResolver.query(Contacts.CONTENT_URI, null, null, null, null);
while (cursor.moveToNext()){
String lookupKey = cursor.getString(cursor.getColumnIndex(Contacts.LOOKUP_KEY));
String groupId = getGroupIdOfContact(lookupKey);
if (targetGroupId.equals(groupId)){
//TODO. delete this contact
}
}
} finally {
if (cursor!=null) cursor.close();
}
}
The above code has not tested but I think that basic idea would be same.
I know how to retrieve the genre of a particular song, (see getting the genres), but I want to retrieve all songs of a particular genre. Since "genre" does not seem to be one of the columns for a media item, I don't know how to do it in a single query, unlike artist or album. Is there an efficient method? Thanx!
Uri uri = Audio.Genres.Members.getContentUri("external", genreID);
String[] projection = new String[]{Audio.Media.TITLE, Audio.Media._ID};
Cursor cur = contentResolver.query(uri, projection, null, null, null);
You can do this by putting together a content URI and querying the MediaStore. Here's some code borrowed from the Android music player:
String [] cols = new String [] {MediaStore.Audio.Genres.NAME};
Cursor cursor = MusicUtils.query(this,
ContentUris.withAppendedId(MediaStore.Audio.Genres.EXTERNAL_CONTENT_URI, Long.valueOf(mGenre)),
cols, null, null, null);
This is the code in MusicUtils:
public static Cursor query(Context context, Uri uri, String[] projection,
String selection, String[] selectionArgs, String sortOrder, int limit) {
try {
ContentResolver resolver = context.getContentResolver();
if (resolver == null) {
return null;
}
if (limit > 0) {
uri = uri.buildUpon().appendQueryParameter("limit", "" + limit).build();
}
return resolver.query(uri, projection, selection, selectionArgs, sortOrder);
} catch (UnsupportedOperationException ex) {
ErrorReporter.getInstance().putCustomData("UnsupportedOperationException", "true");
return null;
}
}
I am working with Android Contact ContentProvider. I have a Phone Number and I need to get the URI of the Photo of the contact associated with this phone number. How can I do it???
I know I can get the raw data of the photo and build an InputStream, but I dont want the input stream, I need the URI.
EDIT: Originally I'm using following code to fetch contact info
Uri uri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phoneNo));
Cursor cursor = context.getContentResolver().query(uri, details, null, null, null);
To get the conatct id using the phone number use the following code:
import android.provider.ContactsContract.PhoneLookup;
public String fetchContactIdFromPhoneNumber(String phoneNumber) {
Uri uri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI,
Uri.encode(phoneNumber));
Cursor cursor = this.getContentResolver().query(uri,
new String[] { PhoneLookup.DISPLAY_NAME, PhoneLookup._ID },
null, null, null);
String contactId = "";
if (cursor.moveToFirst()) {
do {
contactId = cursor.getString(cursor
.getColumnIndex(PhoneLookup._ID));
} while (cursor.moveToNext());
}
return contactId;
}
and use the contact id obtained to get the contatc photo URI. Use the following code for getting photo URI:
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Phone;
public Uri getPhotoUri(long contactId) {
ContentResolver contentResolver = getContentResolver();
try {
Cursor cursor = contentResolver
.query(ContactsContract.Data.CONTENT_URI,
null,
ContactsContract.Data.CONTACT_ID
+ "="
+ contactId
+ " AND "
+ ContactsContract.Data.MIMETYPE
+ "='"
+ ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE
+ "'", null, null);
if (cursor != null) {
if (!cursor.moveToFirst()) {
return null; // no photo
}
} else {
return null; // error in cursor process
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
Uri person = ContentUris.withAppendedId(
ContactsContract.Contacts.CONTENT_URI, contactId);
return Uri.withAppendedPath(person,
ContactsContract.Contacts.Photo.CONTENT_DIRECTORY);
}
Hope this would help.
This solution demonstrates how to get an image from a user contact and then display it in an ImageView.
ImageView profile = (ImageView)findViewById(R.id.imageView1);
Uri my_contact_Uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_URI, String.valueOf(Contact_Id));
InputStream photo_stream = ContactsContract.Contacts.openContactPhotoInputStream(getContentResolver(),my_contact_Uri);
BufferedInputStream buf =new BufferedInputStream(photo_stream);
Bitmap my_btmp = BitmapFactory.decodeStream(buf);
profile.setImageBitmap(my_btmp);
Here's the code from Android Documentation.
Uri contactUri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, contactId);
return Uri.withAppendedPath(contactUri, ContactsContract.Contacts.Photo.CONTENT_DIRECTORY);
You can get PHOTO_URI by NUMBER just use following code also you can use _ID.
public static String getContactPhoto(Context context, String phoneNumber) {
ContentResolver cr = context.getContentResolver();
Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phoneNumber));
Cursor cursor = cr.query(uri, new String[]{ContactsContract.PhoneLookup.PHOTO_URI}, null, null, null);
if (cursor == null) {
return null;
}
String contactImage= null;
if (cursor.moveToFirst()) {
contactImage= cursor.getString(cursor.getColumnIndex(ContactsContract.PhoneLookup.PHOTO_URI));
}
if (!cursor.isClosed()) {
cursor.close();
}
return contactImage;
}
final boolean IS_HONEYCOMB = Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB;
String phoneNumber = "+1 416 385 7805";
ContentResolver contentResolver = context.getContentResolver();
Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phoneNumber));
String[] projection = new String[] {
ContactsContract.Contacts._ID,
ContactsContract.Contacts.LOOKUP_KEY,
IS_HONEYCOMB ? ContactsContract.Contacts.PHOTO_THUMBNAIL_URI : ContactsContract.Contacts._ID,
};
Cursor cursor =
contentResolver.query(
uri,
projection,
null,
null,
null);
if (cursor != null && cursor.moveToNext()) {
long contactId = cursor.getLong(0);
String lookupKey = cursor.getString(1);
String thumbnailUri = cursor.getString(2);
cursor.close();
}
So now if sdk is honeycomb or higher u have thumbnail uri of the contact.
Or you can construct a lookup uri like this:
Uri uri = ContactsContract.Contacts.getLookupUri(contactId, lookupKey);
P.S. If you already know contact id and/or lookup key you can construct a Uri from string:
lookup: content://com.android.contacts/contacts/lookup/{lookup key}/{contact id}
thumbnail: content://com.android.contacts/contacts/{contact id}/photo
So it's better to cache these values.