Is that possible to delete the phone contact from my application - android

I fetched all contacts from phone and listed in list view.i am able to remove the local contact in my listview as well as database now i want to remove the phone contact is that possible. For removing purpose i am using the following code.
if (position == 1) {
db.deleteContact(item_position + 1);
from.remove(item_position);
note.notifyDataSetChanged();
}

get the selected item name and assign it to the name then try the following code.
ContentResolver cr = getContentResolver();
String where = ContactsContract.Data.DISPLAY_NAME + " = ? ";
String[] params = new String[] {name};
ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
ops.add(ContentProviderOperation.newDelete(ContactsContract.RawContacts.CONTENT_URI)
.withSelection(where, params)
.build());
try {
cr.applyBatch(ContactsContract.AUTHORITY, ops);
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (OperationApplicationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Toast.makeText(getApplicationContext(), "Deleted the contact with name '" + name +"'", Toast.LENGTH_SHORT).show();
from.remove(item_position);
note.notifyDataSetChanged();

It may be same as deleting a particular log from the mobile, not sure of how far it can be done.
The code for deleting a particular call log is as follows:
public void DeleteNumFromCallLog(ContentResolver resolver, String strNum) {
try {
String strUriCalls = "content://call_log/calls";
Uri UriCalls = Uri.parse(strUriCalls);
if (null != resolver) {
resolver.delete(UriCalls, CallLog.Calls._ID + "=?",
new String[] { strNum });
}
} catch (Exception e) {
e.getMessage();
}
}

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

if you need to delete contact from Contact Uri
Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null, null);
1.Get all contact from device and store into one container
while (phones.moveToNext())
{
String name=phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
}
phones.close();
2.Select the contact from container`
then pass selected value for performe delete operation
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;
}

Related

Android - Get Contact Photo from phone number

how can I get contact photo from a contact's address (phone number)?
public static Bitmap retrieveContactPhoto(Context context, String number) {
ContentResolver contentResolver = context.getContentResolver();
String contactId = null;
Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(number));
String[] projection = new String[]{ContactsContract.PhoneLookup.DISPLAY_NAME, ContactsContract.PhoneLookup._ID};
Cursor cursor =
contentResolver.query(
uri,
projection,
null,
null,
null);
if (cursor != null) {
while (cursor.moveToNext()) {
contactId = cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.PhoneLookup._ID));
}
cursor.close();
}
Bitmap photo = BitmapFactory.decodeResource(context.getResources(),
R.drawable.default_image);
try {
if(contactId != null) {
InputStream inputStream = ContactsContract.Contacts.openContactPhotoInputStream(context.getContentResolver(),
ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, new Long(contactId)));
if (inputStream != null) {
photo = BitmapFactory.decodeStream(inputStream);
}
assert inputStream != null;
inputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
return photo;
}
I think this vesion works better in all android versions :
public Bitmap getContactsDetails(String address) {
Bitmap bp = BitmapFactory.decodeResource(context.getResources(),
R.drawable.contact_default_picture);
Uri contactUri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(address));
// querying contact data store
Cursor phones = context.getContentResolver().query(contactUri, null, null, null, null);
while (phones.moveToNext()) {
String image_uri = phones.getString(phones.getColumnIndex(
ContactsContract.CommonDataKinds.Phone.PHOTO_URI));
if (image_uri != null) {
try {
bp = MediaStore.Images.Media
.getBitmap(context.getContentResolver(),
Uri.parse(image_uri));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return bp;
}
Call this method to get all contact information.
public void readContacts() {
StringBuffer sb = new StringBuffer();
sb.append("......Contact Details.....");
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null,
null, null, null);
String phone = null;
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);
sb.append("\n Contact Name:" + name);
Cursor pCur = cr.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID
+ " = ?", new String[] { id }, null);
while (pCur.moveToNext()) {
phone = pCur
.getString(pCur
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
sb.append("\n Phone number:" + phone);
System.out.println("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));
emailType = emailCur
.getString(emailCur
.getColumnIndex(ContactsContract.CommonDataKinds.Email.TYPE));
sb.append("\nEmail:" + emailContact + "Email type:" + emailType);
System.out.println("Email " + emailContact
+ " Email Type : " + emailType);
}
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));
sb.append("\n Image in Bitmap:" + bitmap);
System.out.println(bitmap);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
sb.append("\n........................................");
}
textDetail.setText(sb);
}
}
You can use the column below to get the contacts photo uri, ContactsContract.CommonDataKinds.Phone.PHOTO_URI.
This is the function:
public static Bitmap getContactsDetails(String address) {
Bitmap bp = BitmapFactory.decodeResource(context.getResources(),
R.drawable.default_contact_photo);
String selection = ContactsContract.CommonDataKinds.Phone.NUMBER + " = '" + address + "'";
Cursor phones = context.getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, selection,
null, null);
while (phones.moveToNext()) {
String image_uri = phones.getString(phones.getColumnIndex(
ContactsContract.CommonDataKinds.Phone.PHOTO_URI));
if (image_uri != null) {
try {
bp = MediaStore.Images.Media
.getBitmap(context.getContentResolver(),
Uri.parse(image_uri));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return bp;
}
You can make some changes if you want to get Retrieving the larger photo
public Bitmap retrieveContactPhoto(Context context, String number) {
ContentResolver contentResolver = context.getContentResolver();
String contactId = null;
Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(number));
String[] projection = new String[]{ContactsContract.PhoneLookup.DISPLAY_NAME, ContactsContract.PhoneLookup._ID};
Cursor cursor =
contentResolver.query(
uri,
projection,
null,
null,
null);
if (cursor != null) {
while (cursor.moveToNext()) {
contactId = cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.PhoneLookup._ID));
}
cursor.close();
}
Bitmap photo = BitmapFactory.decodeResource(context.getResources(),
R.mipmap.popup);
try {
Uri contactUri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, Long.valueOf(contactId));
Uri displayPhotoUri = Uri.withAppendedPath(contactUri, ContactsContract.Contacts.Photo.DISPLAY_PHOTO);
AssetFileDescriptor fd =
getContentResolver().openAssetFileDescriptor(displayPhotoUri, "r");
InputStream inputStream=fd.createInputStream();
if (inputStream != null) {
photo = BitmapFactory.decodeStream(inputStream);
}
assert inputStream != null;
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
return photo;
}
for Retrieving the thumbnail-sized photo
public InputStream openPhoto(long contactId) {
Uri contactUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId);
Uri photoUri = Uri.withAppendedPath(contactUri, Contacts.Photo.CONTENT_DIRECTORY);
Cursor cursor = getContentResolver().query(photoUri,
new String[] {Contacts.Photo.PHOTO}, null, null, null);
if (cursor == null) {
return null;
}
try {
if (cursor.moveToFirst()) {
byte[] data = cursor.getBlob(0);
if (data != null) {
return new ByteArrayInputStream(data);
}
}
} finally {
cursor.close();
}
return null;
}
for more detail:
Click Here

How to delete contacts from sim in android

I did following code for deleting selected contacts from sim card. but its not deleting and also not throwing any error.
protected void DeleteContacts(ArrayList<String> ids){
int flg = 0;
String[] strids = new String[ids.size()];
strids = ids.toArray(strids);
for (int i = 0; i < strids.length; i++) {
Cursor sims = getActivity().getContentResolver().query(
Uri.parse("content://icc/adn"), null,
"_id=?", new String[]{strids[i]}, null);
sims.moveToFirst();
if (sims.getCount()>0) {
String phoneNumber = sims.getString(sims.getColumnIndex("number"));
boolean val = deleteContact(phoneNumber);
if (!val)
flg=1;
}
if (flg == 0)
Toast.makeText(getActivity(), "Contact Deleted", Toast.LENGTH_SHORT).show();
sims.close();
}
}
public boolean deleteContact(String phone) {
Cursor cur = getActivity().getContentResolver().query(Uri.parse("content://icc/adn"), null, "number=?", new String[] { phone }, 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);
getActivity().getContentResolver().delete(uri, null, null);
return true;
} while (cur.moveToNext());
}
} catch (Exception e) {
System.out.println(e.getStackTrace());
}
return false;
}
You are deleting the contacts from the sqlite database and not the SIM card. For deleting contacts from the SIM card, you need to delete on Uri.parse("content://icc/adn") uri only. But for deletion you need to provide both name and number. Name column has to specified as tag. Check for delete method here https://android.googlesource.com/platform/frameworks/opt/telephony/+/9ebea45a36838f0547a9c30f7cd9c60b03aab3b4/src/java/com/android/internal/telephony/IccProvider.java
Based on my answer here, here is the solution :
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" />

Why Update contacts methods does nothing in android

I write an Update method to update contacts but after i run this on my phone nothing happen
and no contact get update why?
this is my method :
public Boolean UpdateContacts(ArrayList<ContactInfo> encryptedContactsInfoList) {
ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
ContentResolver cr = null;
for (ContactInfo contactInfo : encryptedContactsInfoList) {
try {
String contactId = contactInfo.getContactID();
String contactName = contactInfo.getContactName();
String contactNumber = contactInfo.getContactNumber();
ops.add(ContentProviderOperation
.newUpdate(Data.CONTENT_URI)
.withSelection(
ContactsContract.CommonDataKinds.Phone._ID
+ " = ?", new String[] { contactId })
.withValue(ContactsContract.Data.DISPLAY_NAME,
"asdffgh").build());
cr.applyBatch(ContactsContract.AUTHORITY, ops);
} catch (Exception e) {
Log.d("exception", e.getMessage());
}
}
return true;
}
this is ops after executing the code:
[{"mSelection":"_id \u003d ?","mSelectionArgs":["2302"],"mUri":{"authority":
{"decoded":"com.android.contacts","encoded":"com.android.contacts"},"fragment":{},"path":
{"decoded":"NOT CACHED","encoded":"/data"},"query":{},"scheme":"content","uriString":"NOT
CACHED","host":"NOT CACHED","port":-2},"mValues":{"mValues":
{"display_name":"asdffgh"}},"mType":2,"mYieldAllowed":false}]
any help really appreciate,
best regards.
You get nothing because your ContentResolver is null, so you get an exception in every iteration.
Your app does not crash because you have catch (Exception e) that catches every exception.
try with:
ContentResolver cr = getContentResolver();
also, the applyBatch call should be after the for loop, otherwise you are procesing many times every item, and change ContactsContract.CommonDataKinds.Phone._ID to ContactsContract.Data._ID
try {
for (ContactInfo contactInfo : encryptedContactsInfoList) {
String contactId = contactInfo.getContactID();
String contactName = contactInfo.getContactName();
String contactNumber = contactInfo.getContactNumber();
ops.add(ContentProviderOperation
.newUpdate(Data.CONTENT_URI)
.withSelection(
ContactsContract.Data._ID
+ " = ?", new String[] { contactId })
.withValue(ContactsContract.Data.DISPLAY_NAME,
"asdffgh").build());
}
cr.applyBatch(ContactsContract.AUTHORITY, ops);
} catch (Exception e) {
Log.d("exception", e.getMessage());
}

Get contact photo in Android (API 8) using LOOKUP_URI

I'm trying to get a contact image using its lookup URI.
I succeed getting the DISPLAY_NAME using this code:
Cursor c = context.getContentResolver().query(contactLookupUri,
new String[] { ContactsContract.Contacts.DISPLAY_NAME }, null,
null, null);
But I didn't find a way to get the photo. The Photo.PHOTO option is not valid for the API I'm using, and trying to get it using an inputStream didn't work as well (perhaps I did something wrong there):
InputStream input = ContactsContract.Contacts
.openContactPhotoInputStream(context.getContentResolver(),
contactUri);
Thanks,
Yoel
Eventually I solved it by getting the contact ID and using an inputStream:
public static Uri getContactLookupUri(String contactLookupKey) {
return Uri.withAppendedPath(
ContactsContract.Contacts.CONTENT_LOOKUP_URI, contactLookupKey);
}
public static Bitmap getContactImage(Context context, String contactLookupKey) {
long contactId;
try {
Uri contactLookupUri = getContactLookupUri(contactLookupKey);
Cursor c = context.getContentResolver().query(contactLookupUri,
new String[] { ContactsContract.Contacts._ID }, null, null,
null);
try {
if (c == null || c.moveToFirst() == false) {
return null;
}
contactId = c.getLong(0);
} finally {
c.close();
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
Uri contactUri = ContentUris.withAppendedId(
ContactsContract.Contacts.CONTENT_URI, contactId);
InputStream input = ContactsContract.Contacts
.openContactPhotoInputStream(context.getContentResolver(),
contactUri);
if (input != null) {
return BitmapFactory.decodeStream(input);
} else {
return null;
}
}
The below function return the image uri of your contact_id
/**
* #return the photo URI
*/
public Uri getPhotoUri() {
try {
Cursor cur = this.ctx.getContentResolver().query(
ContactsContract.Data.CONTENT_URI,
null,
ContactsContract.Data.CONTACT_ID + "=" + this.getId() + " AND "
+ ContactsContract.Data.MIMETYPE + "='"
+ ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE + "'", null,
null);
if (cur != null) {
if (!cur.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, Long
.parseLong(getId()));
return Uri.withAppendedPath(person, ContactsContract.Contacts.Photo.CONTENT_DIRECTORY);
}
Also refer this LINK

how to get contact name by sending contact number in android?

if there any method to get contact name by send contact number in android.if any one have idea .
private String getContactName(String string) {
String name=null;
ContentResolver 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.HAS_PHONE_NUMBER));
name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
}
}
return name;
}
I am sending contact number to these method.How to get contact name.
use following method to get contact, from contact provider:
Uri contactUri = Uri.withAppendedPath(Contacts.Phones.CONTENT_FILTER_URL, Uri.encode(string));
Cursor cursor = mContext.getContentResolver().query(contactUri, null, null, null, null);
This cursor will have resultset having number same as string.
I got it by do like these.
public static String getContactName(final String phoneNumber,Context context) {
Uri uri;
String[] projection;
Uri mBaseUri = Contacts.Phones.CONTENT_FILTER_URL;
projection = new String[] { android.provider.Contacts.People.NAME };
try {
Class<?> c = Class
.forName("android.provider.ContactsContract$PhoneLookup");
mBaseUri = (Uri) c.getField("CONTENT_FILTER_URI").get(mBaseUri);
projection = new String[] { "display_name" };
} catch (Exception e) {
}
uri = Uri.withAppendedPath(mBaseUri, Uri.encode(phoneNumber));
Cursor cursor = context.getContentResolver().query(uri, projection, null,
null, null);
String contactName = "";
if (cursor.moveToFirst()) {
contactName = cursor.getString(0);
}
cursor.close();
cursor = null;
return contactName;
}
Try
Uri uri;
String[] projection;
Uri baseUri = Contacts.Phones.CONTENT_FILTER_URL;
projection = new String[] { android.provider.Contacts.People.NAME };
try {
Class<?> c = Class.forName("android.provider.ContactsContract$PhoneLookup");
baseUri = (Uri) c.getField("CONTENT_FILTER_URI").get(baseUri);
projection = new String[] { "display_name" };
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
uri = Uri.withAppendedPath(baseUri, Uri.encode(Uri
.encode(phoneNumber)));
Cursor cursor =mContext.getContentResolver().query(uri,
projection, null, null, null) ;
String fromDisplayName = null;
if (cursor != null) {
if (cursor.moveToFirst()){
fromDisplayName = cursor.getString(0);
}
else{
fromDisplayName="";
}
cursor.close();
} else {
fromDisplayName="";
}
return fromDisplayName;
The Uri android.provider.Contacts.People.NAME is deprecated. But android.provider.ContactsContract$PhoneLookup is available from API level 5 only. Hence it is better to use reflections to support all phones.

Categories

Resources