Android phone contacts lookup function call from adapter.setViewBinder - android

I am trying to list SMS messages with corresponding contact names in list view through following code:
public void btnInboxOnClick {
// Create Inbox box URI
Uri inboxURI = Uri.parse("content://sms/inbox");
// List required columns
String[] reqCols = new String[] { "_id", "address", "body", "person", "date" };
// Get Content Resolver object, which will deal with Content
// Provider
ContentResolver cr = getContentResolver();
// Fetch Inbox SMS Message from Built-in Content Provider
Cursor c = cr.query(inboxURI, reqCols, null, null, "thread_id");
// Attached Cursor with adapter and display in listview
adapter = new SimpleCursorAdapter(this, R.layout.row, c,
new String[] { "body", "address", "date" }, new int[] {
R.id.lblMsg, R.id.lblNumber, R.id.lblDate });
adapter.setViewBinder(new SimpleCursorAdapter.ViewBinder() {
public boolean setViewValue(View aView, Cursor aCursor, int aColumnIndex) {
if (aColumnIndex == aCursor.getColumnIndex("date")) {
String createDate = aCursor.getString(aColumnIndex);
TextView textView = (TextView) aView;
textView.setText(millisToDate(createDate));
return true;
}
else if (aColumnIndex == aCursor.getColumnIndex("address")) {
String PhoneNumber = aCursor.getString(aCursor.getColumnIndex("address"));
TextView textView = (TextView) aView;
// textView.setText(getContactName(MessageBox.this,PhoneNumber)); // this crashes
textView.setText(PhoneNumber); // this works
return true;
}
return false;
}
});
lvMsg.setAdapter(adapter);
}
public static String getContactName(Context context, String phoneNumber) {
ContentResolver cr = context.getContentResolver();
Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phoneNumber));
Cursor cursor = cr.query(uri, new String[]{ContactsContract.PhoneLookup.DISPLAY_NAME}, null, null, null);
if (cursor == null) {
return null;
}
String contactName = null;
if(cursor.moveToFirst()) {
contactName = cursor.getString(cursor.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME));
}
if(cursor != null && !cursor.isClosed()) {
cursor.close();
}
return contactName;
}
App compiles, but crashes. However, if I use the same function code under different circumstances, it works as expected:
public void fillSMS() {
Uri uriSMSURI = Uri.parse("content://sms");
Cursor cur = getContentResolver().query(uriSMSURI, new String[]{"DISTINCT address","body","date","thread_id"}, null, null,"thread_id");
String sms = "";
while (cur.moveToNext()) {
Long d = Long.parseLong(cur.getString(cur.getColumnIndex("date"))); //for retrieve readable date, time
String PhoneNumber = cur.getString(cur.getColumnIndex("address"));
sms += "At :"+ millisToDate(d) +" From :" + getContactName(MainActivity.this,PhoneNumber)+" "+ cur.getString(cur.getColumnIndex("address"))+" : " + "\n"
+ cur.getString(cur.getColumnIndex("body"))+"\n"+"\n";
}
final TextView textView = (TextView) findViewById(R.id.textView1);
textView.setText(sms);
public static String getContactName(Context context, String phoneNumber) {
ContentResolver cr = context.getContentResolver();
Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phoneNumber));
Cursor cursor = cr.query(uri, new String[]{ContactsContract.PhoneLookup.DISPLAY_NAME}, null, null, null);
if (cursor == null) {
return null;
}
String contactName = null;
if(cursor.moveToFirst()) {
contactName = cursor.getString(cursor.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME));
}
if(cursor != null && !cursor.isClosed()) {
cursor.close();
}
return contactName;
}
}
public static String millisToDate(long currentTime) {
String finalDate;
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(currentTime);
Date date = calendar.getTime();
SimpleDateFormat outputFormat = new SimpleDateFormat("MMM-dd-yyyy HH:mm");
finalDate = outputFormat.format(date);
return finalDate;
}
What am I doing wrong? Please help.

Well, this was a beginner stupidity one.
Forgot to add permission in AndroidManifest.xml :
<uses-permission android:name="android.permission.READ_CONTACTS"></uses-permission>
Hope this will be informative to someone.

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

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

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

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