contact exists in contacts - android

I have phone number. Is there any way to check whether the phone number exists in contacts database in the device or not? Depending on that I need have move further in my app. Please suggest or if any one can have sample code snippet please provide.
The below is the code I wrote:
public boolean contactExists(Activity _activity, String number) {
String[] mPhoneNumberProjection = { PhoneLookup._ID, PhoneLookup.NUMBER, PhoneLookup.DISPLAY_NAME };
Cursor cur = _activity.getContentResolver().query(number, mPhoneNumberProjection, null, null, null);
try {
if (cur.moveToFirst()) {
return true;
}
} finally {
if (cur != null)
cur.close();
}
return false;
}// contactExists
Thanks in Advance...

public boolean contactExists(Activity _activity, String number) {
if (number != null) {
Uri lookupUri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(number));
String[] mPhoneNumberProjection = { PhoneLookup._ID, PhoneLookup.NUMBER, PhoneLookup.DISPLAY_NAME };
Cursor cur = _activity.getContentResolver().query(lookupUri, mPhoneNumberProjection, null, null, null);
try {
if (cur.moveToFirst()) {
return true;
}
} finally {
if (cur != null)
cur.close();
}
return false;
} else {
return false;
}
}// contactExists
Handled nullpointer exception.

A minor change in your code ::
You need to have lookupUri..
public boolean contactExists(Activity _activity, String number) {
Uri lookupUri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(number));
String[] mPhoneNumberProjection = { PhoneLookup._ID, PhoneLookup.NUMBER, PhoneLookup.DISPLAY_NAME };
Cursor cur = _activity.getContentResolver().query(lookupUri, mPhoneNumberProjection, null, null, null);
try {
if (cur.moveToFirst()) {
return true;
}
} finally {
if (cur != null)
cur.close();
}
return false;
}// contactExists

I tried the code above on an ice cream device (SIII) and it didnt work
so after some search i ended up creating this method (which is working nicely )
private boolean isContact(String incommingNumber) {
Cursor cursor =null;
String name = null;
try {
Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(incommingNumber));
cursor = MainService.this.getContentResolver().query(uri, new String[] { PhoneLookup.DISPLAY_NAME }, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
name = cursor.getString(cursor.getColumnIndex(PhoneLookup.DISPLAY_NAME));
}
} finally {
if(cursor!=null){
cursor.close();
}
}
return Util.hasValue(name);
}

Related

Hard Reset/Data Wipe Android Device through android application

I am developing an Android Application to wipe all data from Android including photos, videos, contacts, messages, apps,call logs, application data etc. programmatically. I wish to achieve this with an Android Application only and not through adb.
The approach I am thinking of somehow I manage to Clear data from phone and rewrite the memory with some junk files or binary data 1010 say. (Its just an idea!)
All I have managed to do is delete photos,videos,images,contacts,call logs,messages from Device using Cursor and getContentResolver. But we can recover that using third party Data Recover Softwares.
I have also reset the device using device administrator but the cons of this is the data can be recovered through it.
So, all i need is which approach to follow for hard resetting the device.
I have used below code .
public static void deleteAllContacts(Context activity) {
ContentResolver contentResolver = activity.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);
}
}
public static void deleteAllCallLog(Context activity) {
activity.getContentResolver().delete(CallLog.Calls.CONTENT_URI, null, null);
}
/* public static void deleteAllMessages(Context activity) {
ContentResolver localContentResolver = activity.getContentResolver();
Uri localUri = Uri.parse("content://sms");
for (int i = localContentResolver.delete(Telephony.Sms.CONTENT_URI, null, null); i == 1; i = localContentResolver.delete(localUri, null, null)) {
}
}*/
public static void deleteVideoFiles(Activity activity) {
String[] videoProjection = {MediaStore.Video.Media._ID, MediaStore.Video.Media.DATA,
MediaStore.Video.Media.DISPLAY_NAME, MediaStore.Video.Media.SIZE};
Cursor videoCursor = activity.managedQuery(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, videoProjection, null, null, null);
int count = videoCursor.getCount();
for (int i = 0; i < count; i++) {
int indexID = videoCursor.getColumnIndexOrThrow(MediaStore.Video.Media._ID);
videoCursor.moveToPosition(i);
String path = getVideoFilePath(videoCursor.getString(indexID), activity);
Log.d("Video Path", path);
File file = new File(path);
boolean isDeleted = file.delete();
Log.d("isDELETED", String.valueOf(isDeleted));
}
videoCursor.close();
}
public static void deleteAudioFiles(Activity activity) {
String[] proj = {MediaStore.Audio.Media._ID, MediaStore.Audio.Media.DISPLAY_NAME, MediaStore.Audio.Media.SIZE};
Cursor audioCursor = activity.getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, proj, null, null, null);
if (audioCursor != null) {
if (audioCursor.moveToFirst()) {
do {
int indexId = audioCursor.getColumnIndexOrThrow(MediaStore.Audio.Media._ID);
String path = getAudioFilePath(audioCursor.getString(indexId), activity);
Log.d("Audio Path", path);
File file = new File(path);
boolean isDeleted = file.delete();
Log.d("isDELETED", String.valueOf(isDeleted));
} while (audioCursor.moveToNext());
}
}
if (audioCursor != null) audioCursor.close();
}
public static void deleteImageFiles(Activity activity) {
Uri u = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
String[] projection = {MediaStore.Images.ImageColumns.DATA};
Cursor c = null;
SortedSet<String> dirList = new TreeSet<String>();
String[] directories = null;
if (u != null) {
c = activity.managedQuery(u, projection, null, null, null);
}
if ((c != null) && (c.moveToFirst())) {
do {
String tempDir = c.getString(0);
tempDir = tempDir.substring(0, tempDir.lastIndexOf("/"));
try {
dirList.add(tempDir);
} catch (Exception e) {
}
}
while (c.moveToNext());
directories = new String[dirList.size()];
dirList.toArray(directories);
}
for (int i = 0; i < dirList.size(); i++) {
File imageDir = new File(directories[i]);
File[] imageList = imageDir.listFiles();
if (imageList == null)
continue;
for (File imagePath : imageList) {
try {
if (imagePath.isDirectory()) {
imageList = imagePath.listFiles();
}
if (imagePath.getName().contains(".jpg") || imagePath.getName().contains(".JPG")
|| imagePath.getName().contains(".jpeg") || imagePath.getName().contains(".JPEG")
|| imagePath.getName().contains(".png") || imagePath.getName().contains(".PNG")
|| imagePath.getName().contains(".gif") || imagePath.getName().contains(".GIF")
|| imagePath.getName().contains(".bmp") || imagePath.getName().contains(".BMP")
) {
Log.d("Absolute Path", imagePath.getAbsolutePath());
File file = new File(imagePath.getAbsolutePath());
boolean isDeleted = file.delete();
Log.d("iSDELETED", String.valueOf(isDeleted));
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
public static String getAudioFilePath(String contentId, Activity activity) {
Uri theMediaUri = Uri.withAppendedPath(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, contentId);
String[] projection = {MediaStore.Audio.Media.DATA};
Cursor mCur = activity.getContentResolver().query(theMediaUri, projection, null, null, null);
int column_index = mCur.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA);
mCur.moveToFirst();
return mCur.getString(column_index);
}
public static String getVideoFilePath(String contentId, Activity activity) {
Uri theMediaUri = Uri.withAppendedPath(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, contentId);
String[] projection = {MediaStore.Video.Media.DATA};
Cursor mCur = activity.getContentResolver().query(theMediaUri, projection, null, null, null);
int column_index = mCur.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA);
mCur.moveToFirst();
return mCur.getString(column_index);
}
public static void deleteSMS(Context context) {
/* try {
Uri uriSms = Uri.parse("content://sms/inbox");
Cursor c = context.getContentResolver().query(uriSms, new String[]{"_id", "body"}, null, null, null);
if (c != null && c.moveToFirst()) {
do {
long id = c.getLong(0);
Log.d("Body : ", c.getString(1));
context.getContentResolver().delete(
Uri.parse("content://sms/" + id), null, null);
Log.e("Message:", "Message is Deleted successfully");
} while (c.moveToNext());
}
if (c != null) {
c.close();
}
} catch (Exception e) {
Log.e("Exception", e.toString());
}*/
Cursor c =context.getContentResolver().query(Uri.parse("content://sms/"), new String[]{"_id", "body"}, null, null,null);
try {
while (c.moveToNext()) {
int id = c.getInt(0);
int isDeleted = context.getContentResolver().delete(Uri.parse("content://sms/" + id), null, null);
Log.d("IS DELETED" , String.valueOf(isDeleted));
}
}catch(Exception e){
Log.e("Delete Sms","Error deleting sms",e);
}finally {
c.close();
}
}

Android retrieve contact name always returns false

I am trying to check whether given name is in phone contact or not, but it always returns false, i cant figure out what mistake i have done
public boolean ContactNotFound(String no, String name) {
if (no != null) {
Uri lookupUri = Uri.withAppendedPath(
PhoneLookup.CONTENT_FILTER_URI, Uri.encode(name));
String[] mPhoneNumberProjection = { PhoneLookup._ID,
PhoneLookup.NUMBER, PhoneLookup.DISPLAY_NAME };
Cursor cur = con.getContentResolver().query(lookupUri,
mPhoneNumberProjection, null, null, null);
LogUtil.d("Count -->" + cur.getCount());
if (cur.getCount() > 0) {
try {
if (cur.moveToFirst()) {
return true;
}
} finally {
if (cur != null)
cur.close();
}
return false;
} else {
return false;
}
} else {
return false;
}
}
Kindly help me to figure out the issue
I suggest you to save all your contact names in arraylist temporarily and then check name using arrayList.contains(name) method

Retrieve contact image on Android

I am currently working on an Android project where I am attempting to lookup a contact phone number in the device and retrieve the contact information such as contact name and contacts image. Getting the contract name is working fine, however, a null pointer is being thrown when trying to get the photo uri.
Below is the code I am using:
public ContactInformation getContactInfoFromPhoneNumber(String number)
{
ContactInformation contactInformation = new ContactInformation();
if (number == null)
{
return null;
}
number = number.replace(" ", "");
if (number.startsWith("+"))
{
number = number.substring(3);
}
ContentResolver contentResolver = context.getContentResolver();
Uri uri = ContactsContract.Data.CONTENT_URI;
String[] projection = new String[] {ContactsContract.PhoneLookup._ID, ContactsContract.PhoneLookup.DISPLAY_NAME};
String selection = "REPLACE (" + ContactsContract.CommonDataKinds.Phone.NUMBER + ", \" \" , \"\" ) LIKE ?";
String[] selectionArgs = { "%" + number };
Cursor cursor = contentResolver.query(uri, projection, selection, selectionArgs, null);
if (cursor.moveToFirst())
{
contactInformation.contactName = cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.PhoneLookup.DISPLAY_NAME));
contactInformation.photoUri = cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.PHOTO_URI));
cursor.close();
return contactInformation;
}
else
{
cursor.close();
return null;
}
}
Update
Below is my updated code based on Itzik Samara's answer.
Below is how I am doing my contact lookup:
public ContactInformation getContactInfoFromPhoneNumber(String number)
{
ContactInformation contactInformation = new ContactInformation();
if (number == null)
{
return null;
}
number = number.replace(" ", "");
if (number.startsWith("+"))
{
number = number.substring(3);
}
ContentResolver contentResolver = context.getContentResolver();
Uri uri = ContactsContract.Data.CONTENT_URI;
String[] projection = new String[] {ContactsContract.PhoneLookup._ID, ContactsContract.PhoneLookup.DISPLAY_NAME};
String selection = "REPLACE (" + ContactsContract.CommonDataKinds.Phone.NUMBER + ", \" \" , \"\" ) LIKE ?";
String[] selectionArgs = { "%" + number };
Cursor cursor = contentResolver.query(uri, projection, selection, selectionArgs, null);
if (cursor.moveToFirst())
{
contactInformation.contactName = cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.PhoneLookup.DISPLAY_NAME));
contactInformation.photoBase64String = getContactPhoto(cursor.getInt(cursor.getColumnIndexOrThrow(ContactsContract.Contacts._ID)));
cursor.close();
return contactInformation;
}
else
{
cursor.close();
return null;
}
}
Below is my getContactPhoto function:
private String getContactPhoto(int contactID)
{
Uri contactUri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, contactID);
Uri photoUri = Uri.withAppendedPath(contactUri, ContactsContract.Contacts.Photo.CONTENT_DIRECTORY);
Cursor cursor = context.getContentResolver().query(photoUri, new String[]{ContactsContract.Contacts.Photo.PHOTO},
null, null, null);
if (cursor == null)
{
return null;
}
if (cursor.getCount() > 0)
{
while (cursor.moveToNext()) {
byte[] data = cursor.getBlob(0);
String base64String = Base64.encodeToString(data, Base64.DEFAULT);
cursor.close();
return base64String;
}
}
return null;
}
It's failing on the if statement and jumping out of the if straight to return null as if there is nothing in the cursor.
this function works for me :
private byte[] getContactPhoto(Context context,long contact_id) {
Uri contactUri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, contact_id);
Uri photoUri = Uri.withAppendedPath(contactUri,ContactsContract.Contacts.Photo.CONTENT_DIRECTORY);
Cursor cursor = context.getContentResolver().query(photoUri, new String[]{ContactsContract.Contacts.Photo.PHOTO}, null, null, null);
if(cursor == null)
return null;
try {
if(cursor.getCount() > 0) {
if (cursor.moveToFirst()) {
byte[] data = cursor.getBlob(0);
cursor.close();
if (data != null)
return data;
}
}
}
finally {
cursor.close();
}
return null;
}
private void getContacts(Context context) {
ContentResolver cr = context.getContentResolver();
Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI,null,null,null,null);
try {
if (cursor.getCount() > 0) {
while (cursor.moveToNext()) {
long contact_id = cursor.getLong(cursor.getColumnIndex(ContactsContract.Contacts._ID));
Contact friend = new Contact();
String name= cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
String email = getContactEmail(context, contact_id);
if(!name.contains("#") && !email.matches("")) {
friend.setName(name);
friend.setEmail(email);
friend.setImage(getContactPhoto(context, contact_id));
friend.setPhone(getContactMobilePhoneNumber(context, contact_id));
mContacts.add(friend);
}
}
}
}
finally {
cursor.close();
}
}

java.lang.IllegalArgumentException: column'_data' does not exist

public static String getFilePathFromUri(Uri uri, Context c) {
try {
String filePath = null;
String scheme = uri.getScheme();
if (scheme != null && scheme.equals("content")) {
ContentResolver contentResolver = c.getContentResolver();
Cursor cursor = contentResolver.query(uri, null, null, null,
null);
cursor.moveToFirst();
filePath = cursor.getString(cursor
.getColumnIndexOrThrow(Images.Media.DATA));
}
return filePath;
} catch (Exception e) {
//java.lang.illegalArgumentException: column'_data' does not exist
return null;
}
}
I get this Exception When the Image is from Picasa folder.
// try this way,hope this will help you...
public String getAbsolutePath(Uri uri) {
if(Build.VERSION.SDK_INT >= 19){
String id = uri.getLastPathSegment().split(":")[1];
final String[] imageColumns = {MediaStore.Images.Media.DATA };
final String imageOrderBy = null;
Uri tempUri = getUri();
Cursor imageCursor = getContentResolver().query(tempUri, imageColumns,
MediaStore.Images.Media._ID + "="+id, null, imageOrderBy);
if (imageCursor.moveToFirst()) {
return imageCursor.getString(imageCursor.getColumnIndex(MediaStore.Images.Media.DATA));
}else{
return null;
}
}else{
String[] projection = { MediaColumns.DATA };
Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
if (cursor != null) {
int column_index = cursor.getColumnIndexOrThrow(MediaColumns.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} else
return null;
}
}

How to use "lookupKey" to get Contact Image?

I have lookupkeys for contact, now I want to obtain Contact Images as Bitmap/InputStream using these lookupkeys. Android documentation helps getting Images but with contacts id not lookupkey.
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;
}
Running from pillar to post but no help. Thanks
Edit Dated 04-09-2012
Tried as suggested by #Sreejith Krishnan R but received the following exceptions in logcat
09-04 03:16:26.359: E/AndroidRuntime(24008): java.lang.IllegalArgumentException: URI: content://com.android.contacts/contacts/lookup/0r272-382C544E2C562C382C4E582C42.2649i11.1987r6285-382C544E2C562C382C4E582C42.1987r6440-382C544E2C562C382C4E582C42.2829r6475-382C544E2C562C382C4E582C42/photo, calling user: com.xyz, calling package:com.xyz
09-04 03:16:26.359: E/AndroidRuntime(24008): at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:144)
09-04 03:16:26.359: E/AndroidRuntime(24008): at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:114)
[Updated]
Now this can be used since API level 5
public Bitmap getAvatar(Context context, String lookupKey){
Uri uri = getDataUri(context, lookupKey);
if (uri == null){
return null;
}
Cursor cursor = context.getContentResolver().query(
uri,
new String[] {ContactsContract.Data.DATA15},
null,
null,
null
);
if (cursor == null){
return null;
}
try{
if (cursor.moveToFirst()){
byte [] bytes = cursor.getBlob(0);
InputStream inputStream = new ByteArrayInputStream(bytes);
return BitmapFactory.decodeStream(inputStream);
}
} finally {
cursor.close();
}
return null;
}
public Uri getDataUri(Context context, String lookupKey){
Cursor cursor = context.getContentResolver().query(
Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_LOOKUP_URI, lookupKey),
new String[] {ContactsContract.Contacts.PHOTO_ID},
null,
null,
null
);
if (cursor == null){
return null;
}
try {
if (cursor.moveToFirst()){
long id = cursor.getLong(0);
/**http://developer.android.com/reference/android/provider/ContactsContract.ContactsColumns.html#PHOTO_ID
* If PHOTO_ID is null, consult PHOTO_URI or PHOTO_THUMBNAIL_URI,
* which is a more generic mechanism for referencing the contact photo,
* especially for contacts returned by non-local directories (see ContactsContract.Directory).
*/
if (id == 0){
if (Build.VERSION.SDK_INT < 11){
return null;
}
return getPhotoThumbnailUri(context, lookupKey);
}
return ContentUris.withAppendedId(ContactsContract.Data.CONTENT_URI, id);
}
} finally {
cursor.close();
}
return null;
}
//Available only for API level 11+
public Uri getPhotoThumbnailUri(Context context, String lookupKey){
Cursor cursor = context.getContentResolver().query(
Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_LOOKUP_URI, lookupKey),
new String[] {ContactsContract.Contacts.PHOTO_THUMBNAIL_URI},
null,
null,
null
);
if (cursor == null){
return null;
}
try{
if (cursor.moveToFirst()){
return Uri.parse(cursor.getString(0));
}
} finally {
cursor.close();
}
return null;
}

Categories

Resources