Retrieve contact image on Android - 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();
}
}

Related

How to retrieve company name from the selected contact

Using ContactsContract I am able to retrieve and display selected mobile number and the relevant contact name.
But instead of returning the company name it's returning the mobile number again.
The intent I use to select a specific phone number when there are multiple numbers
Intent calContctPickerIntent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
calContctPickerIntent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE);
startActivityForResult(calContctPickerIntent, 1);
here is the main code
#Override
public void onActivityResult(int reqCode, int resultCode, Intent data) {
super.onActivityResult(reqCode, resultCode, data);
switch (reqCode) {
case (1):
if (resultCode == Activity.RESULT_OK) {
Uri contctDataVar = data.getData();
Cursor contctCursorVar = getContentResolver().query(contctDataVar, null, null, null, null);
if (contctCursorVar.getCount() > 0) {
while (contctCursorVar.moveToNext()) {
String ContctUidVar = contctCursorVar.getString(contctCursorVar.getColumnIndex(ContactsContract.Contacts._ID));
String ContctNamVar = contctCursorVar.getString(contctCursorVar.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
String Companyname = contctCursorVar.getString(contctCursorVar.getColumnIndex(ContactsContract.CommonDataKinds.Organization.DATA));
Log.i("Names", ContctNamVar);
if (Integer.parseInt(contctCursorVar.getString(contctCursorVar.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
// Query phone here. Covered next
String ContctMobVar = contctCursorVar.getString(contctCursorVar.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
String Companyname2 = contctCursorVar.getString(contctCursorVar.getColumnIndex(ContactsContract.CommonDataKinds.Organization.COMPANY));
mobile.setText(ContctMobVar);
custname.setText(ContctNamVar);
companyname.setText(Companyname2);
Log.i("Number", ContctMobVar);
}
}
}
}
break;
}
}
I need to find a way to retrieve the company name saved under the selected contact.
You may try something like this :
ContentResolver mContentResolver = this.getContentResolver();
Cursor contacts = cr.query(ContactsContract.Contacts.CONTENT_URI,
null, null, null, null);
String mContactId = contacts.getString(contacts.getColumnIndex(ContactsContract.Contacts._ID));
String mRawContactId = getRawContactID(mContactId);
String mCompanyName = getCompanyName(mRawContactId);
private String getRawContactID(String contactId) {
String[] projection = new String[]{ContactsContract.RawContacts._ID};
String selection = ContactsContract.RawContacts.CONTACT_ID + "=?";
String[] selectionArgs = new String[]{contactId};
Cursor c = mContentResolver.query(ContactsContract.RawContacts.CONTENT_URI, projection, selection, selectionArgs, null);
if (c == null) return null;
int rawContactId = -1;
if (c.moveToFirst()) {
rawContactId = c.getInt(c.getColumnIndex(ContactsContract.RawContacts._ID));
}
c.close();
return String.valueOf(rawContactId);
}
private String getCompanyName(String rawContactId) {
try {
String orgWhere = ContactsContract.Data.RAW_CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?";
String[] orgWhereParams = new String[]{rawContactId,
ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE};
Cursor cursor = mContentResolver.query(ContactsContract.Data.CONTENT_URI,
null, orgWhere, orgWhereParams, null);
if (cursor == null) return null;
String name = null;
if (cursor.moveToFirst()) {
name = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Organization.COMPANY));
}
cursor.close();
return name;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
With the help of the solution provided by #Shiva Snape I was able to solve the problem.
Code for button to call contacts app and select the relevant number
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE);
startActivityForResult(intent, 1);
Code to collect Contact Number, Name and company name.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (data != null) {
Uri uri = data.getData();
if (uri != null) {
Cursor c = null;
try {
c = getContentResolver().query(uri, new String[]{
ContactsContract.CommonDataKinds.Phone.CONTACT_ID,
ContactsContract.CommonDataKinds.Phone.TYPE,
ContactsContract.CommonDataKinds.Phone.NUMBER,
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME},
null, null, null);
ContentResolver mContentResolver = this.getContentResolver();
if (c != null && c.moveToFirst()) {
String number = c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
String name = c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String contactId = c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID));
String rawContactId = getRawContactId(contactId);
String companyName = getCompanyName(rawContactId);
int type = c.getInt(1);
showSelectedNumber(type, number);
}
} finally {
if (c != null) {
c.close();
}
}
}
}
}
private String getCompanyName(String rawContactId) {
try {
String orgWhere = ContactsContract.Data.RAW_CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?";
String[] orgWhereParams = new String[]{rawContactId,
ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE};
Cursor cursor = getContentResolver().query(ContactsContract.Data.CONTENT_URI,
null, orgWhere, orgWhereParams, null);
if (cursor == null) return null;
String Vname = null;
if (cursor.moveToFirst()) {
Vname = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Organization.COMPANY));
}
cursor.close();
return Vname;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
private String getRawContactId(String contactId) {
String[] projection = new String[]{ContactsContract.RawContacts._ID};
String selection = ContactsContract.RawContacts.CONTACT_ID + "=?";
String[] selectionArgs = new String[]{contactId};
Cursor c = getContentResolver().query(ContactsContract.RawContacts.CONTENT_URI, projection, selection, selectionArgs, null);
if (c == null) return null;
int rawContactId = -1;
if (c.moveToFirst()) {
rawContactId = c.getInt(c.getColumnIndex(ContactsContract.RawContacts._ID));
}
c.close();
return String.valueOf(rawContactId);
}
public void showSelectedNumber(int type, String number) {
Toast.makeText(this, type + ": " + number, Toast.LENGTH_LONG).show();
}
}
Thanks to the Stack Overflow community for helping me out. Hope this becomes helpful to others.

Get phone number by contact name

I’m trying to get phone number from contacts by providing the phone number. what I've done so far:
public static String getPhone(Context context, String displayName) {
ContentResolver cr = context.getContentResolver();
Uri uri = CommonDataKinds.Phone.CONTENT_URI;
String selection = CommonDataKinds.Phone.DISPLAY_NAME+" LIKE '%" + displayName + "&'";
Cursor cursor = cr.query(uri, new String[]{CommonDataKinds.Phone._ID,CommonDataKinds.Phone.DISPLAY_NAME,CommonDataKinds.Phone.NUMBER}, selection, null, null);
if (cursor == null) {
return null;
}
String contactName = null;
if(cursor.moveToFirst()) {
contactName = cursor.getString(cursor.getColumnIndex(CommonDataKinds.Phone.NUMBER));
}
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
//Log.d("Contact",contactName.toString());
return contactName;
}
Try this code out. You will need to set the permission in the manifest "android.permission.READ_CONTACTS" on true.
public String getPhoneNumber(String name, Context context) {
String ret = null;
String selection = ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME+" like'%" + name +"%'";
String[] projection = new String[] { ContactsContract.CommonDataKinds.Phone.NUMBER};
Cursor c = context.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
projection, selection, null, null);
if (c.moveToFirst()) {
ret = c.getString(0);
}
c.close();
if(ret==null)
ret = "Unsaved";
return ret;
}
UPDATE:
This code snippet will allow you to read all messages from a particular contact:
StringBuilder smsBuilder = new StringBuilder();
final String SMS_URI_INBOX = "content://sms/inbox";
final String SMS_URI_ALL = "content://sms/";
try {
Uri uri = Uri.parse(SMS_URI_INBOX);
String[] projection = new String[] { "_id", "address", "person", "body", "date", "type" };
Cursor cur = getContentResolver().query(uri, projection, "address='123456789'", null, "date desc");
if (cur.moveToFirst()) {
int index_Address = cur.getColumnIndex("address");
int index_Person = cur.getColumnIndex("person");
int index_Body = cur.getColumnIndex("body");
int index_Date = cur.getColumnIndex("date");
int index_Type = cur.getColumnIndex("type");
do {
String strAddress = cur.getString(index_Address);
int intPerson = cur.getInt(index_Person);
String strbody = cur.getString(index_Body);
long longDate = cur.getLong(index_Date);
int int_Type = cur.getInt(index_Type);
smsBuilder.append("[ ");
smsBuilder.append(strAddress + ", ");
smsBuilder.append(intPerson + ", ");
smsBuilder.append(strbody + ", ");
smsBuilder.append(longDate + ", ");
smsBuilder.append(int_Type);
smsBuilder.append(" ]\n\n");
} while (cur.moveToNext());
if (!cur.isClosed()) {
cur.close();
cur = null;
}
} else {
smsBuilder.append("no result!");
} // end if
}
} catch (SQLiteException ex) {
Log.d("SQLiteException", ex.getMessage());
}

Get the SMS/MMS thread_id from the phone number

I need to get the thread_id of the mms-sms/conversations Android content provider, this is what I have done so far:
public long findThreadIdFromPhoneNumber(Context context, PhoneNumber phoneNumber) {
Uri.Builder uriBuilder = Uri.withAppendedPath(Uri.parse(CONTENT_SMSMMS+"/"), "threadID").buildUpon();
// phoneNumber.msisdn() return the String phone number
uriBuilder.appendQueryParameter("recipient", phoneNumber.msisdn());
long threadId = -1L;
Cursor cursor = null;
try {
cursor = context.getContentResolver().query(
uriBuilder.build(),
new String[] { Contacts._ID },
null, null, null);
if (cursor != null && cursor.moveToFirst()) {
threadId = cursor.getLong(0);
}
} finally {
if (cursor != null) {
cursor.close();
}
}
return threadId;
}
The problem is that this code create new threads in the content provider, and I don't need that, I just need to return the thread_id if the conversation exists and -1 if it do not exists.
I also tried this code:
public long findThreadIdFromPhoneNumber(Context context, PhoneNumber phoneNumber) {
long threadId = -1L;
Cursor cursor = null;
try {
if (context==null || context.getContentResolver()==null || phoneNumber==null || phoneNumber.msisdn()==null)
return threadId;
cursor = context.getContentResolver().query(
Uri.parse(CONTENT_SMSMMS_CONVERSATIONS),
// phoneNumber.msisdn() return the String phone number
null, "address='"+phoneNumber.msisdn()+"' ",
null, null
);
if (cursor != null && cursor.moveToFirst()) {
if (cursor.getColumnIndex("thread_id")>=0)
threadId = cursor.getLong(cursor.getColumnIndex("thread_id"));
}
} catch (Exception e) {
e.printStackTrace();
String number = (phoneNumber!=null && phoneNumber.msisdn()!=null) ? phoneNumber.msisdn() : "";
Logcat.e("Error during findThreadIdFromPhoneNumber for "+number+": "+e.getMessage(), e);
return threadId;
} finally {
if (cursor != null) {
cursor.close();
}
}
return threadId;
}
But this code give me an external NullPointerException in the ContentResolver in some phones, and it works in other:
java.lang.NullPointerException
at android.os.Parcel.readException(Parcel.java:1437)
at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:185)
at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:137)
at android.content.ContentProviderProxy.query(ContentProviderNative.java:385)
at android.content.ContentResolver.query(ContentResolver.java:417)
at android.content.ContentResolver.query(ContentResolver.java:360)
at com.mypackage.android.sms.SmsMmsManager.findThreadIdFromPhoneNumber(SmsMmsManager.java:115)
Use this uri for fetching
ContentResolver cr = context.getContentResolver();
Cursor pCur = cr.query(
Uri.parse("content://mms-sms/canonical-addresses"), new String[]{"_id"},
"address" + " = ?",
new String[]{your_address}, null);
String thread_id = null;
if (pCur != null) {
if (pCur.getCount() != 0) {
pCur.moveToNext();
thread_id = pCur.getString(pCur.getColumnIndex("_id"));
}
pCur.close();
}
public MessageObjects getSms2(Context context , String number) {
ContentResolver contentResolver = context.getContentResolver();
Uri uri = Uri.parse("content://sms/");
Cursor cursor = contentResolver.query(uri, null, "thread_id IS NOT NULL) GROUP BY (thread_id AND address=?", new String[]{number}, "date DESC");
String displayName;
String formattedDate = "";
String photoUri = null;
MessageObjects contct = new MessageObjects();
while (cursor.moveToNext()) {
displayName = "";
long key = cursor.getLong(cursor.getColumnIndex("_id"));
long threadId = cursor.getLong(cursor.getColumnIndex("thread_id"));
String address = cursor.getString(cursor.getColumnIndex("address")); // phone #
long date = cursor.getLong(cursor.getColumnIndex("date"));
Date callDayTime = new Date(Long.valueOf(date));
String body = cursor.getString(cursor.getColumnIndex("body"));
String person = cursor.getString(cursor.getColumnIndex("person"));
contct.setThreadId(threadId);
contct.setNumber(address);
contct.setTime(date);
contct.setMsg(body);
contct.setPerson(displayName);
}
cursor.close();
return contct;
}

Getting contact details takes too long in Android

I am trying to get id, firstName, lastName, fullName and photo from contacts. I used the following code for that,
but it takes too long to fetch data, at least 10 seconds. I used this code on thread so my activity won't freeze
but it takes too long to get all the data.
String[] projection = new String[] {ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME_ALTERNATIVE,
ContactsContract.Contacts.DISPLAY_NAME,
};
Cursor cursor = getContentResolver().query(
ContactsContract.Contacts.CONTENT_URI, projection, 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) {
ContactClass info = new ContactClass();
info.setid(contactId);
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 lastName = "";
String displayname = cursor
.getString(cursor
.getColumnIndex(Contacts.DISPLAY_NAME_ALTERNATIVE));
if (!firstName.equals(displayname)) {
lastName = nameCursor
.getString(nameCursor
.getColumnIndex(Data.DATA3));
}
// check lastName Value
if (firstName.equals(null)
&& lastName.equals(null)) {
info.setfirstname("unknown name");
} else if (firstName.equals(null)) {
info.setlastname(lastName);
} else if (lastName.equals(null)) {
info.setfirstname(firstName);
} else {
info.setfirstname(firstName);
info.setlastname(lastName);
}
} while (nameCursor.moveToNext());
nameCursor.close();
info.setphoto(retrieveContactPhoto(contactId));
contactinfo.add(info);
} catch (Exception e) {
}
}
phones.close();
}
catch (Exception t) {
}
} while (cursor.moveToNext());
cursor.close();
retrieveContactPhoto():
private String retrieveContactPhoto(String contactID) {
Uri photoUri = ContentUris.withAppendedId(
ContactsContract.Contacts.CONTENT_URI,
Long.parseLong(contactID));
final Cursor image = getContentResolver().query(photoUri,
PHOTO_ID_PROJECTION, null, null,
ContactsContract.Contacts._ID + " ASC");
try {
Integer thumbnailId = null;
if (image.moveToFirst()) {
thumbnailId = image.getInt(image
.getColumnIndex(ContactsContract.Contacts.PHOTO_ID));
Uri uri = ContentUris.withAppendedId(
ContactsContract.Data.CONTENT_URI, thumbnailId);
image.close();
if (uri.toString().equals(
"content://com.android.contacts/data/0"))
return null;
return uri.toString();
}
} finally {
image.close();
}
return null;
}
What do you recommend I should do to improve the perfomance of the above code?
i try this code to fetch my contact
try {
String select = "((" + Contacts.DISPLAY_NAME + " NOTNULL) AND ("
+ Contacts.HAS_PHONE_NUMBER + "=1) AND ("
+ Contacts.DISPLAY_NAME + " != '' ))";
Cursor c = cntx.getContentResolver().query(Contacts.CONTENT_URI, CONTACTS_SUMMARY_PROJECTION, select,
null, Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC");
for(int i=0;i<c.getCount();i++)
{
// contactWrap.clear();
try {
contactId = 0;
String hasPhone = "";
display_name = "";
phoneNumber = "";
c.moveToPosition(i);
contactId = c.getLong(0);
display_name = c.getString(1);
hasPhone = c.getString(7);
if (hasPhone.equalsIgnoreCase("1"))
hasPhone = "true";
else
hasPhone = "false" ;
if (Boolean.parseBoolean(hasPhone))
{
Cursor phones = cntx.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = "+ contactId,null, null);
while (phones.moveToNext())
{
int indexPhoneType = phones.getColumnIndexOrThrow(Phone.TYPE);
String phoneType = phones.getString(indexPhoneType);
phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
String lookupKey = phones.getString(phones.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));
contactWrap.add(new ContactsWrapper(contactId, display_name, phoneNumber,lookupKey,false,color_string));
}
// map.put(contactId, new ArrayList<ContactsWrapper>(contactWrap));
phones.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
ohk u can take contactID from this cursor or your code now this is my method which will give u contact photo just pass contact ID in it
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;
}
Hope this will help u Best of luck dude

How do i get the SMS Sender Contact (Person) saved name using "content://sms/inbox"

In my App i want to retrieve the SMS sender saved Name using below code but it always return null. Please suggest me whats the convenient way to get the sender name.
Uri SMS_INBOX = Uri.parse("content://sms/inbox");
Cursor c = getContentResolver().query(SMS_INBOX, null, null, null, null);
android.util.Log.i("COLUMNS", Arrays.toString(c.getColumnNames()));
try {
if(c.getCount()>0)
{
while (c.moveToNext()){
Log.d("SMSss", "Contact : "+c.getString(2)+"\n"
+"msg : "+c.getString(11)+"\n"
+"ID : "+c.getString(0)+"\n"
+"Person : "+c.getString(3));
}
}
} catch (Exception e) {
Log.d("mmmmmmmmm"," "+ e.getStackTrace());
}
i am using following permission in menifest
<uses-permission android:name="android.permission.READ_SMS"/>
<uses-permission android:name="android.permission.READ_CALL_LOG"/>
<uses-permission android:name="android.permission.READ_CONTACTS"/>
<uses-permission android:name="android.permission.WRITE_CONTACTS"/>
Please suggest me how to get. Thanks in advance.
By this way you can get the saved contact name from inbox..
call the method getAllSms() to get the details..
public void getAllSms() {
Uri message = Uri.parse("content://sms/");
ContentResolver cr = getContentResolver();
Cursor c = cr.query(message, null, null, null, null);
startManagingCursor(c);
int totalSMS = c.getCount();
if (c.moveToFirst()) {
for (int i = 0; i < totalSMS; i++) {
Log.d("SMSss",
"Contact number : "
+ c.getString(c
.getColumnIndexOrThrow("address"))
+ "\n"
+ "msg : "
+ c.getColumnIndexOrThrow("body")
+ "\n"
+ "ID : "
+ c.getString(c.getColumnIndexOrThrow("_id"))
+ "\n"
+ "Person : "
+ getContactName(
getApplicationContext(),
c.getString(c
.getColumnIndexOrThrow("address"))));
c.moveToNext();
}
}
c.close();
}
public String getContactName(Context context, String phoneNumber) {
ContentResolver cr = context.getContentResolver();
Uri uri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI,
Uri.encode(phoneNumber));
Cursor cursor = cr.query(uri,
new String[] { PhoneLookup.DISPLAY_NAME }, null, null, null);
if (cursor == null) {
return null;
}
String contactName = null;
if (cursor.moveToFirst()) {
contactName = cursor.getString(cursor
.getColumnIndex(PhoneLookup.DISPLAY_NAME));
}
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
return contactName;
}
Uri uriInbox = Uri.parse("content://sms/inbox");
Cursor c = getContentResolver().query(uriInbox, null, null, null, null);
if (c.moveToFirst()) {
for (int i = 0; i < c.getCount(); i++) {
String name = null;
String phone = "";
String _id = c.getString(c.getColumnIndexOrThrow("_id"));
String thread_id = c.getString(c.getColumnIndexOrThrow("thread_id"));
String msg = c.getString(c.getColumnIndexOrThrow("body"));
String type = c.getString(c.getColumnIndexOrThrow("type"));
String timestamp = c.getString(c.getColumnIndexOrThrow("date"));
phone = c.getString(c.getColumnIndexOrThrow("address"));
name = Function.getContactbyPhoneNumber(getApplicationContext(), c.getString(c.getColumnIndexOrThrow("address")));
c.moveToNext();
}
}
c.close();
Finally your getContactbyPhoneNumber method:
public String getContactbyPhoneNumber(Context c, String phoneNumber) {
Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phoneNumber));
String[] projection = {ContactsContract.PhoneLookup.DISPLAY_NAME};
Cursor cursor = c.getContentResolver().query(uri, projection, null, null, null);
if (cursor == null) {
return phoneNumber;
}else {
String name = phoneNumber;
try {
if (cursor.moveToFirst()) {
name = cursor.getString(cursor.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME));
}
} finally {
cursor.close();
}
return name;
}
}
Courtesy: http://www.androstock.com/tutorials/create-sms-app-android-android-studio-part-2.html

Categories

Resources