Get phone number by contact name - android

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

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.

How to get Contact's company name in android

I'm trying to import contacts into my app, but struggling with getting the company name. Here's my code:
public List<ContactItem> getContactList(){
ArrayList<ContactItem> contactList = new ArrayList<ContactItem>();
Uri contactUri = ContactsContract.Contacts.CONTENT_URI;
String[] PROJECTION = new String[] {
ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.Contacts.HAS_PHONE_NUMBER,
};
String SELECTION = ContactsContract.Contacts.HAS_PHONE_NUMBER + "='1'";
Cursor contacts = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, PROJECTION, SELECTION, null, null);
if (contacts.getCount() > 0)
{
while(contacts.moveToNext()) {
ContactItem aContact = new ContactItem();
int idFieldColumnIndex = 0;
int nameFieldColumnIndex = 0;
int numberFieldColumnIndex = 0;
int companyFieldColumnIndex = 0;
String contactId = contacts.getString(contacts.getColumnIndex(ContactsContract.Contacts._ID));
nameFieldColumnIndex = contacts.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME);
if (nameFieldColumnIndex > -1)
{
aContact.setName(contacts.getString(nameFieldColumnIndex));
}
// Tried to get a company, but
// this always returns -1
companyFieldColumnIndex = contacts.getColumnIndex(ContactsContract.CommonDataKinds.Organization.COMPANY);
if (companyFieldColumnIndex > -1)
{
Log.d(TAG, "getContactList: starts");
aContact.setCompany(contacts.getString(companyFieldColumnIndex));
}
PROJECTION = new String[] {ContactsContract.CommonDataKinds.Phone.NUMBER};
final Cursor phone = managedQuery(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, PROJECTION, ContactsContract.Data.CONTACT_ID + "=?", new String[]{String.valueOf(contactId)}, null);
if(phone.moveToFirst()) {
while(!phone.isAfterLast())
{
numberFieldColumnIndex = phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
if (numberFieldColumnIndex > -1)
{
aContact.setPhoneNum(phone.getString(numberFieldColumnIndex));
phone.moveToNext();
TelephonyManager mTelephonyMgr;
mTelephonyMgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
if (!mTelephonyMgr.getLine1Number().contains(aContact.getPhoneNum()))
{
contactList.add(aContact);
}
}
}
}
phone.close();
}
contacts.close();
}
return contactList;
}
I add a comment in my code, where i'm trying to get the contact's company name, but i always get -1. Some contacts have the company name, so something wrong in this part of code. How to get the company properly?
First thing, you are passing Projection which doesn't contains anything related to Company name so of course you won't get it.
Other thing which I am not sure is, you need to pass contact's RawId instead of ID to fetch the Company name. Here's something how you should do it,
String contactId = contacts.getString(contacts.getColumnIndex(ContactsContract.Contacts._ID));
String rawContactId = getRawContactId(contactId);
String companyName = getCompanyName(rawContactId);
& here are the functions you'll need:
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);
}
and:
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;
}
}

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

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

Unable to read all SMS from inbox

Here is my code:
private void readSMS() throws IOException {
// TODO Auto-generated method stub
Log.d("Read SMS","Called");
ContentResolver cr = context.getContentResolver();
Uri uri = Uri.parse("content://sms/inbox");
String smsBackup;
Cursor messagesCursor = cr.query(uri, new String[] { "_id","address","body","person"}, null,null, null);
smsBackup = "SMS Back UP (Total Message(s)::"+messagesCursor.getCount()+") \n\n";
String smsfile = "SMS" + "_" + System.currentTimeMillis()+".txt";
storage_path = Environment.getExternalStorageDirectory().toString() + File.separator + smsfile;
FileOutputStream mFileOutputStream = new FileOutputStream(storage_path,true);
mFileOutputStream.write(smsBackup.getBytes());
String name = null,smsString;
int smsCounter = 1;
if(messagesCursor.getCount() > 0){
while(messagesCursor.moveToNext()){
name = null;
name = getName(messagesCursor.getString(messagesCursor.getColumnIndex("address")));
if(name==null)
name = "Sender : " + messagesCursor.getString(messagesCursor.getColumnIndex("address"));
smsString = "SMS No : "+smsCounter+"\nSender : "+name +"\n"+ "Message : "+messagesCursor.getString(messagesCursor.getColumnIndex("body")) + "\n\n";
mFileOutputStream.write(smsString.getBytes());
Log.d("Message","::"+smsString+"Length::"+smsString.length());
smsString = null;
Log.d("Message","written::"+smsCounter);
smsCounter++;
}
messagesCursor.close();
file = new File(storage_path);
mFileOutputStream.close();
Log.d("MSGFile","written");
}
}
private String getName(String number1) {
// TODO Auto-generated method stub
Log.d("get name","Called");
//Log.d("get name",number1);
Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,null, null, null, null);
if(cur.getCount() > 0){
String[] projection = new String[] {ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.NUMBER };
Cursor names = getContentResolver().query(uri, projection, null, null, null);
int indexName = names.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
int indexNumber = names.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
names.moveToFirst();
do {
String name = names.getString(indexName);
//Log.e("Name new:", name);
String number = names.getString(indexNumber);
//Log.e("Number new:","::"+number);
if(number1.contains(number)){
cur.close();
return name;
}
} while (names.moveToNext());
}
cur.close();
return null;
}
I am getting warning also : W/CursorWrapperInner(22787): Cursor finalized without prior close()
use the bellow code get the contacts
private void readMessagesFromDeviceDB()
{
Uri SMSURI = Uri.parse("content://sms/inbox");
String[] projection = new String[]{"_id", "address", "body", "date"};
Cursor cursor = null;
try
{
cursor = getContentResolver().query(SMSURI
, projection
, null //selection
, null //selectionArgs
, null); //sortOrder
if (cursor != null && cursor.moveToFirst())
{
do
{
int id = cursor.getInt(cursor.getColumnIndex("_id")); //returns a unique thread id
String address = cursor.getString(cursor.getColumnIndex("address")); //returns contact no.
String body = cursor.getString(cursor.getColumnIndex("body")); //returns message body
String date = cursor.getString(cursor.getColumnIndex("date")); //returns date( when was the message received )
SimpleDateFormat formatter = new SimpleDateFormat("dd, MMM HH:mm");
date = formatter.format(new Date(Long.parseLong(date)));
// System.out.println("id: " + id + " address: " + address + " body: " + body + " date: " + date);
}
while (cursor.moveToNext());
}
} finally {
if (cursor != null)
{
cursor.close();
}
}
}

Categories

Resources