how to get contact name by sending contact number in android? - 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.

Related

How to delete specific contact from phonebook [duplicate]

This question already has answers here:
How to delete a particular contact using contact id?
(4 answers)
Closed 5 years ago.
Uri contactUri = Uri.withAppendedPath(ContactsContract.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(ContactsContract.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);
}
} while (cur.moveToNext());
}
} catch (Exception e) {
System.out.println(e.getStackTrace());
} finally {
cur.close();
}
Try the following method:
private static final Uri CONTACT_CONTENT_URI = ContactsContract.Contacts.CONTENT_URI;
public static boolean deleteContact(final Context context, final String contactId) {
if (null != context) {
final Uri uri = Uri.withAppendedPath(CONTACT_CONTENT_URI, contactId);
final ContentResolver contentResolver = context.getContentResolver();
try {
final int deletedRowCount = contentResolver.delete(uri, null, null);
return deletedRowCount > 0;
} catch (final Exception e) {
Log.e(TAG, e.toString());
}
}
return false;
}

How to list all video files on device

I want to get all videos path in android (Internal and External storage both), I have tried use:
List<String> paths = new ArrayList<String>();
File directory = new File("/system" OR "/mnt/sdcard");
File[] files = directory.listFiles();
for (int i = 0; i < files.length; ++i) {
if(files[i].getAbsolutePath().contains(".mp4")) {
paths.add(files[i].getAbsolutePath());
}
}
but I can not get all of video lists from my device.
Here is your solution must try if you want to really a actual result.
public ArrayList<String> getAllMedia() {
HashSet<String> videoItemHashSet = new HashSet<>();
String[] projection = { MediaStore.Video.VideoColumns.DATA ,MediaStore.Video.Media.DISPLAY_NAME};
Cursor cursor = getContext().getContentResolver().query(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, projection, null, null, null);
try {
cursor.moveToFirst();
do{
videoItemHashSet.add((cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATA))));
}while(cursor.moveToNext());
cursor.close();
} catch (Exception e) {
e.printStackTrace();
}
ArrayList<String> downloadedList = new ArrayList<>(videoItemHashSet);
return downloadedList;
}
You need to make your search recursive. Something like:
void findVideos(File dir, ArrayList<String> list){
for (File file : dir.listFiles()) {
if (file.isDirectory()) findVideos(file, list);
else if(file.getAbsolutePath().contains(".mp4")) list.add(file.getAbsolutePath());
}
}
List<VideoClass> videoItems = new ArrayList<VideoClass>();
ContentResolver contentResolver = getContentResolver();
Uri uri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
Cursor cursor = contentResolver.query(uri, null, null, null, null);
//looping through all rows and adding to list
if (cursor != null && cursor.moveToFirst()) {
do {
String title = cursor.getString(cursor.getColumnIndex(MediaStore.Video.Media.TITLE));
Uri contentUri = ContentUris.withAppendedId(
MediaStore.Video.Media.EXTERNAL_CONTENT_URI, cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Video.Media._ID)));
Bitmap vimage =
null;
try {
vimage = getApplicationContext().getContentResolver().loadThumbnail(
contentUri, new Size(640, 480), null);
} catch (IOException e) {
e.printStackTrace();
}
VideoClass videoModel = new VideoClass();
videoModel.setTitle(title);
videoModel.setMain_video(String.valueOf(contentUri));
videoModel.setImage(vimage);
videoItems.add(videoModel);
} while (cursor.moveToNext());
}
return videoItems;
String title = cursor.getString(cursor.getColumnIndex(MediaStore.Video.Media.TITLE));
Uri contentUri = ContentUris.withAppendedId(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Video.Media._ID)));
Bitmap vimage = null;
try {
vimage = getApplicationContext().getContentResolver().loadThumbnail(contentUri, new Size(640, 480), null);
} catch (IOException e) {
e.printStackTrace();
}

Android fetching phone number, name and photo from contacts taking too much time

This code fetching contacts, name and photo from contact list but it is taking too much time in fetching all these.
So my problem is if user has more then 500 contacts then its taking to much time so how to decreasing its fetching time.
I have seen many posts on Stack Overflow but unable to find solution.
public void fetchContacts() {
list = new ArrayList<PersonDetails>();
String phoneNumber = null;
//Uri CONTENT_URI = ContactsContract.Contacts.CONTENT_URI;
Uri CONTENT_URI= ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
String _ID = ContactsContract.Contacts._ID;
String DISPLAY_NAME = ContactsContract.Contacts.DISPLAY_NAME;
String HAS_PHONE_NUMBER = ContactsContract.Contacts.HAS_PHONE_NUMBER;
Uri PhoneCONTENT_URI = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
String Phone_CONTACT_ID = ContactsContract.CommonDataKinds.Phone.CONTACT_ID;
String NUMBER = ContactsContract.CommonDataKinds.Phone.NUMBER;
// StringBuffer output = new StringBuffer();
String[] PROJECTION = new String[] {
ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.Contacts.HAS_PHONE_NUMBER, };
String SELECTION = ContactsContract.Contacts.HAS_PHONE_NUMBER
+ "='1'";
ContentResolver contentResolver = getContentResolver();
Cursor cursor = contentResolver.query(CONTENT_URI, PROJECTION,
SELECTION, null, null);
// Loop for every contact in the phone
if (cursor.getCount() > 0) {
while (cursor.moveToNext()) {
//Log.e("i", i + "");
PersonDetails personDetails = null;
String contact_id = cursor.getString(cursor
.getColumnIndex(_ID));
String name = cursor.getString(cursor
.getColumnIndex(DISPLAY_NAME));
int hasPhoneNumber = Integer.parseInt(cursor
.getString(cursor
.getColumnIndex(HAS_PHONE_NUMBER)));
if (hasPhoneNumber > 0) {
// Query and loop for every phone number of the
// contact
String Phone_Projection[] = new String[] { Phone.NUMBER };
Cursor phoneCursor = contentResolver.query(
PhoneCONTENT_URI, Phone_Projection,
Phone_CONTACT_ID + " = ?",
new String[] { contact_id }, null);
while (phoneCursor.moveToNext()) {
phoneNumber = phoneCursor.getString(phoneCursor
.getColumnIndex(NUMBER));
// output.append("\n Phone number:" +
// phoneNumber);
}
phoneCursor.close();
if (phoneNumber != null
&& phoneNumber.length() >= 10) {
Uri ur = null;
try {
Uri person = ContentUris
.withAppendedId(
ContactsContract.Contacts.CONTENT_URI,
Long.parseLong(contact_id));
ur = Uri.withAppendedPath(
person,
ContactsContract.Contacts.Photo.CONTENT_DIRECTORY);
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
personDetails = new PersonDetails();
if (name != null) {
personDetails.setName(name);
}
if (phoneNumber != null) {
//Log.e("Phone", phoneNumber);
personDetails.setSocialId(phoneNumber);
}
if (ur != null) {
//Log.e("URI", ur.toString());
personDetails.setPhotoUrl(ur.toString());
}
personDetails.setSocialFlag(5);
}
}
if (personDetails != null) {
list.add(personDetails);
}
}
}
try {
if (cursor != null) {
cursor.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}

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

Is that possible to delete the phone contact from my application

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

Categories

Resources