Android - Trouble deleting only contacts with a specified note - android

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

Related

How to fetch recent and favourite contacts in android?

I have been trying to fetch recent and favorites contacts but every time i get error .
i am storing contacts in database after fetching .
cannot read column -1
and sometimes it says cursor not initialized properly.
please help me .
Here is my code.
ContentResolver cr = getActivity().getContentResolver();
/* Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null,
null, null, null );*/
Cursor cur=cr.query(CallLog.Calls.CONTENT_URI,null,CallLog.Calls.DATE, null,null);
String phone = null;
String emailContact = null;
String image_uri;
Bitmap bitmap;
final SQLiteDatabase mDb = db.getWritableDatabase();
mDb.beginTransaction();
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)));`*/
}
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(getActivity().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));
ContentValues contentValues = new ContentValues();
contentValues.put("contact_name", name);
contentValues.put("contact_number",phone);
contentValues.put("contact_email",emailContact);
contentValues.put("contact_image",image_uri);
mDb.insert(TABLE_CONTACT, null, contentValues);
emailContact="";
phone="";
}
mDb.setTransactionSuccessful();
mDb.endTransaction();
cur.close();
}
You're querying the CallLog table:
Cursor cur=cr.query(CallLog.Calls.CONTENT_URI,null,CallLog.Calls.DATE, null,null)
and then trying to get info from that cursor with fields from the Contacts table:
cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
Obviously, that's not how it should work.
Also, your selection:
CallLog.Calls.DATE
is not a legal selection string.
How you should do it:
To get a list of starred (favourites) contacts:
String[] projection = new String[] { Contacts._ID }; // you can add more fields you need here
Cursor cursor = cr.query(Contacts.CONTENT_URI, projection, Contacts.STARRED + "=1", null, null);
To get a list of contacts with in the last 24 hours:
String[] projection = new String[] { Contacts._ID }; // you can add more fields you need here
int oneDay = (1000 * 60 * 60 * 24);
long last24h = (System.currentTimeMillis() - oneDay);
Cursor cursor = cr.query(Contacts.CONTENT_URI, projection, Contacts. LAST_TIME_CONTACTED + ">" + last24h, null, null);
I know till now you may have solved that error but still i want to answer for further help for seekers. The code for favorite contact fetching is working you just need to add following in the projection:
String[] projection = new String[] { ContactsContract.Contacts._ID,
ContactsContract.Contacts.LOOKUP_KEY,
ContactsContract.Contacts.HAS_PHONE_NUMBER,
ContactsContract.Contacts.DISPLAY_NAME_PRIMARY};

How to delete sim card contact in android

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" />

Checkable Contact List in Android

I want to make a checkable Contact List that should be stored by the application, allow the users to place checks on some contacts, and store users' preferences.
I want to know whether a preference activity can be used to list all contacts as checkboxes,
or whether a custom listview can allow me to save the users preferences for the app?
you can get contact data with following code:
Cursor cursor = getContentResolver().query(
ContactsContract.Contacts.CONTENT_URI, null, null,
null, null);
cursor.moveToFirst();
if (cursor.getCount() > 0) {
do {
try {
contactId = cursor
.getString(cursor
.getColumnIndex(ContactsContract.Contacts._ID));
Uri contactUri = ContentUris.withAppendedId(
Contacts.CONTENT_URI,
Long.parseLong(contactId));
Uri dataUri = Uri.withAppendedPath(contactUri,
Contacts.Data.CONTENT_DIRECTORY);
Cursor phones = getContentResolver()
.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID
+ " = " + contactId,
null, null);
if (phones.getCount() > 0) {
try {
Cursor nameCursor = getContentResolver()
.query(dataUri,
null,
Data.MIMETYPE + "=?",
new String[] { StructuredName.CONTENT_ITEM_TYPE },
null);
nameCursor.moveToFirst();
do {
String firstName = nameCursor
.getString(nameCursor
.getColumnIndex(Data.DATA2));
String displayname = cursor
.getString(cursor
.getColumnIndex(Contacts.DISPLAY_NAME_ALTERNATIVE));
lastName = nameCursor
.getString(nameCursor
.getColumnIndex(Data.DATA3));
} while (nameCursor.moveToNext());
nameCursor.close();
} catch (Exception e) {
}
}
phones.close();
}
catch (Exception t) {
}
} while (cursor.moveToNext());
}
after get list of your contact name or anything that you want you need create custom adapter to show this data, for creating the custom list see this link and this.
//////////////////////
EDIT:
you can get phone number with following code:
String number = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));

Deleting all Contacts programmatically

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" />

Delete all contacts in a group

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.

Categories

Resources