I have the following code to load all contacts with their pictures
public static void getAllContactWithNumberAndNameAndPhoto(Context context,
ArrayList<ContactInfo> mContactList, boolean starred) {
ContentResolver cr = context.getContentResolver();
Cursor cur = null;
if (starred == true) {
cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null,
"starred=?", new String[] { "1" }, null);
} else {
cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null,
null, null);
}
if (cur.getCount() > 0) {
while (cur.moveToNext()) {
ContactInfo item = new ContactInfo();
String id = cur.getString(cur
.getColumnIndex(ContactsContract.Contacts._ID));
String name = cur
.getString(cur
.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
// Uri photo = PhoneUtils.getPhotoUriFromID(context, id);
String starredValue = cur.getString(cur
.getColumnIndex(ContactsContract.Contacts.STARRED));
boolean isFav = false;
if (starredValue.equals("1"))
isFav = true;
if (Integer
.parseInt(cur.getString(cur
.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
Cursor pCur = cr.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID
+ " = ?", new String[] { id }, null);
while (pCur.moveToNext()) {
String phoneNo = pCur
.getString(pCur
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
item.addPhone(removeCharactersFromPhoneNumber(phoneNo));
}
pCur.close();
// if (photo != null) {
//
// item.setPhoto(photo.toString());
// }
item.setName(name);
item.setFavorite(isFav);
item.setRecent(false);
mContactList.add(item);
}
}
cur.close();
}
}
and the following code to load contact picture Uri
public static Uri getPhotoUriFromID(Context context, String id) {
try {
Cursor cur = context
.getContentResolver()
.query(ContactsContract.Data.CONTENT_URI,
null,
ContactsContract.Data.CONTACT_ID
+ "="
+ id
+ " AND "
+ ContactsContract.Data.MIMETYPE
+ "='"
+ ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE
+ "'", null, null);
if (cur != null) {
if (!cur.moveToFirst()) {
return null;
}
} else {
return null;
}
cur.close();
} catch (Exception e) {
e.printStackTrace();
return null;
}
Uri person = ContentUris.withAppendedId(
ContactsContract.Contacts.CONTENT_URI, Long.parseLong(id));
return Uri.withAppendedPath(person,
ContactsContract.Contacts.Photo.CONTENT_DIRECTORY);
}
every thing is working fine but too slow about 40 second for 1000 contact, when I comment the part of loading image it takes 18 sec, so how can I load image uri in the same query of loading contact to minimize the waiting time of the user.
For displaying the images of contacts you can use Universal Image Loader library. It's great for handling multiple images. You can use a default image to display initially and as soon as the contact's image is loaded the library will display that image.
This is how you display image in this library:
ImageLoader.getInstance().displayImage(img, imageView, options);
where img is the image, imageView is the ImageView where you want to display that image, options is the object of DisplayImageOptions of UniversalImageLoader library.
Related
How to get the real path of multiple selected pictures from gallery stocked in an array? I was searching and I just found how to get the real path of one picture:
public static String getFileNameByUri(Context context, Uri uri)
{
String fileName="unknown";//default fileName
Uri filePathUri = uri;
if (uri.getScheme().toString().compareTo("content")==0)
{
Cursor cursor = context.getContentResolver().query(uri, null, null, null, null);
if (cursor.moveToFirst())
{
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);//Instead of "MediaStore.Images.Media.DATA" can be used "_data"
filePathUri = Uri.parse(cursor.getString(column_index));
fileName = filePathUri.getLastPathSegment().toString();
}
}
else if (uri.getScheme().compareTo("file")==0)
{
fileName = filePathUri.getLastPathSegment().toString();
}
else
{
fileName = fileName+"_"+filePathUri.getLastPathSegment();
}
return fileName;
}
I am using the code below to access the phone numbers and the names of the contact. I want to add to this function a way to also add the photo of the contact.
void loadContacts() {
ContentResolver contentResolver=getContentResolver();
Cursor cursor=contentResolver.query(ContactsContract.Contacts.CONTENT_URI,null,null,null,null);
if(cursor.getCount() > 0) {
while (cursor.moveToNext()) {String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
int hasPhoneNumber = Integer.parseInt(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER)));
if (hasPhoneNumber > 0) {
Cursor cursor2 = contentResolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[]{id}, null);
while (cursor2.moveToNext()) {
String phoneNumber = cursor2.getString(cursor2.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
make_contact(name,phoneNumber);
}
cursor2.close();
}
}
}
cursor.close();
}
For Bitmap Image,
private Bitmap retrieveContactPhoto(String contactID) {
Bitmap photo = null;
try {
InputStream inputStream = ContactsContract.Contacts.openContactPhotoInputStream(getContentResolver(),
ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, new Long(contactID)));
if (inputStream != null) {
photo = BitmapFactory.decodeStream(inputStream);
}
assert inputStream != null;
inputStream.close();
return photo ;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
By using contact Id you can retrieve bitmap image and set to imageview.
try this
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);
}
now set to image
Uri u = objItem.getPhotoUri();
if (u != null) {
mPhotoView.setImageURI(u);
} else {
mPhotoView.setImageResource(R.drawable.ic_contact_picture_2);
}
I am trying to save an image, and alert the Gallery about the new image. The image is not immediately shown in the gallery, but it can take even a few hour to refresh. I use the following code:
String title = "title";
String r = MediaStore.Images.Media.insertImage(getContentResolver(), State.pictureWithDekor, title, title);
Uri uri = Uri.parse(r);
MediaScannerConnection.scanFile(this,
new String[] { uri.getPath() }, null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
Log.i("TAG", "Finished scanning " + path);
}
});
the value of r after the insertImage is content://media/external/images/media/2082, the uri in the onScanCompleted is null.
What am I doing wrong?
The problem is that the path returned from the MediaStore.Images.Media.insertImage is not a phisical path. to get the real path, use:
public String getRealPathFromURI(Context context, Uri contentUri) {
Cursor cursor = null;
try {
String[] proj = { MediaStore.Images.Media.DATA };
cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} finally {
if (cursor != null) {
cursor.close();
}
}
}
Source: Get filename and path from URI from mediastore
I am using
Uri uriSms = Uri.parse("content://mms-sms/conversations?simple=true");
Cursor cursor = getContentResolver().query(uriSms, null,null,null,null);
cursor.moveToLast();
while (cursor.moveToPrevious())
{
String recipient_ids= cursor.getString(cursor.getColumnIndex("recipient_ids"));
String body = cursor.getString(cursor.getColumnIndex("snippet"));
}
to get a list of sms conversation.
The "recipient_ids" returns some value Like 302, 301 259 etc. What I want is a function where i will pass the "recipient_ids" as perameter and it will return the display name of the contact (If available else the Number)
These methods help you to achieve what you want:
getContactByRecipientId - to get contact number by recipientId.
getContactbyPhoneNumber - to get display name by phone number.
public String getContactByRecipientId(long recipientId) {
String contact = "";
Uri uri = ContentUris.withAppendedId(Uri.parse("content://mms-sms/canonical-address"), recipientId);
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
try {
if (cursor.moveToFirst()) {
contact = getContactbyPhoneNumber(cursor.getString(0));
}
} finally {
cursor.close();
}
return contact;
}
public String getContactbyPhoneNumber(String phoneNumber) {
Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phoneNumber));
String[] projection = {ContactsContract.PhoneLookup.DISPLAY_NAME, ContactsContract.PhoneLookup.NORMALIZED_NUMBER };
Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
String name = null;
String nPhoneNumber = phoneNumber;
try {
if (cursor.moveToFirst()) {
nPhoneNumber = cursor.getString(cursor.getColumnIndex(ContactsContract.PhoneLookup.NORMALIZED_NUMBER));
name = cursor.getString(cursor.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME));
}
} finally {
cursor.close();
}
if(name != null){ // if there is a display name, then return that
return name;
}else{
return nPhoneNumber; // if there is not a display name, then return just phone number
}
}
Please check this code
private void fetchInbox() {
Uri inboxURI = Uri.parse("content://sms/inbox");
String[] reqCols = new String[]{"_id", "address", "body"};
ContentResolver cr = getContentResolver();
Cursor c = cr.query(inboxURI, reqCols, null, null, null);
adapter = new SimpleCursorAdapter(this, R.layout.row, c,
new String[]{"body", "address"}, new int[]{
R.id.lblMsg, R.id.lblNumber}, 0);
}
I'm trying to get name of Contact List from phone's contacts list, I have error on first line of try: ContentResolver cr = ContactFragment.getActivity().getContentResolver();
Any help?
ContactFragment.java
private String refreshData() {
String namedata = "";
try {
/**************************************************/
ContentResolver cr = ContactFragment.getActivity().getContentResolver();
Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI, null,
"DISPLAY_NAME = '" + namedata + "'", null, null);
if (cursor.moveToFirst()) {
String contactId =
cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
//
// Get all phone numbers.
//
Cursor phones = cr.query(Phone.CONTENT_URI, null,
Phone.CONTACT_ID + " = " + contactId, null, null);
while (phones.moveToNext()) {
String number = phones.getString(phones.getColumnIndex(namedata));
phones.close();
}
}
}
Try Like This :
Set this tag in manifest file:
<uses-permission android:name="android.permission.READ_CONTACTS" />
Try this code :
Cursor cursor = null;
try {
cursor = context.getContentResolver().query(Phone.CONTENT_URI, null, null, null, null);
int contactIdIdx = cursor.getColumnIndex(Phone._ID);
int nameIdx = cursor.getColumnIndex(Phone.DISPLAY_NAME);
int phoneNumberIdx = cursor.getColumnIndex(Phone.NUMBER);
int photoIdIdx = cursor.getColumnIndex(Phone.PHOTO_ID);
cursor.moveToFirst();
do {
String idContact = cursor.getString(contactIdIdx);
String name = cursor.getString(nameIdx);
String phoneNumber = cursor.getString(phoneNumberIdx);
//...
} while (cursor.moveToNext());
} catch (Exception e) {
e.printStackTrace();
} finally {
if (cursor != null) {
cursor.close();
}
}