to send email using Intent - android

In my project,I have retrieved my call log and sms Data and want it to send through email in background.
Retrieved data code is:-(in WakefulBroadcastReceiver)
private Context mContext;
#Override
public void onReceive(Context context, Intent intent) {
mContext = context;
getSMSData();
getCallLogData();
}
private void getSMSData() {
ContentResolver contentResolver = mContext.getContentResolver();
// use content://sms/inbox/ for received and content://sms/sent/ for sent messages
Uri uri = Uri.parse("content://sms/");
String selection = "date BETWEEN ? AND ? ";
long currentTime = System.currentTimeMillis();
long pastThreeHour = currentTime - (AlarmManager.INTERVAL_HOUR * 3);
String[] selectionArgs = { "" + pastThreeHour, "" + currentTime };
Cursor cursor = contentResolver.query(uri, null, selection, selectionArgs, "date DESC");
if (cursor != null && cursor.getCount() > 0) {
while (cursor.moveToNext()) {
String number = cursor.getString(cursor.getColumnIndex("address")); // check for null
String date = cursor.getString(cursor.getColumnIndex("date")); // convert to date its long
String message_text = cursor.getString(cursor.getColumnIndex("body"));
String type = cursor.getString(cursor.getColumnIndex("type")); // check type and get names
// send email from here
sendSMSEmail(number, date, message_text, type);
}
}
cursor.close();
}
private void getCallLogData() {
Uri uri = Uri.parse("content://call_log/calls");
String[] projection = new String[] { Calls.TYPE, Calls.NUMBER, Calls.DATE, Calls.CACHED_NAME, Calls.DURATION };
String selection = "date BETWEEN ? AND ? ";
long currentTime = System.currentTimeMillis();
long pastThreeHour = currentTime - (AlarmManager.INTERVAL_HOUR * 3);
String[] selectionArgs = { "" + pastThreeHour, "" + currentTime };
Cursor cursor = mContext.getContentResolver().query(uri, projection, selection, selectionArgs, "date DESC");
if (cursor != null && cursor.getCount() > 0) {
while (cursor.moveToNext()) {
String num = cursor.getString(cursor.getColumnIndex(android.provider.CallLog.Calls.NUMBER));
// convert long date to date
String date = cursor.getString(cursor.getColumnIndex(android.provider.CallLog.Calls.DATE));
String name = cursor.getString(cursor.getColumnIndex(android.provider.CallLog.Calls.CACHED_NAME));
String duration = cursor.getString(cursor.getColumnIndex(android.provider.CallLog.Calls.DURATION));
int type = Integer.parseInt(cursor.getString(cursor.getColumnIndex(android.provider.CallLog.Calls.TYPE)));
String typeName = null;
switch (type) {
case 1:
typeName = "Incoming";
break;
case 2:
typeName = "Outgoing";
break;
case 3:
typeName = "Missed";
break;
}
sendCallEmail(num, date, name, duration, typeName);
}
}
}
private void sendCallEmail(String num, String date, String name, String duration, String typeName) {
// TODO Auto-generated method stub
}
private void sendSMSEmail(String number, String date, String message_text, String type) {
// TODO Auto-generated method stub
}
}
Actually I can't understand how to send these retrieved data to my mail id.
Mail Id should be provided by the user only.
Please help me to send mail.
Thanks in Advance.

Intent email = new Intent(Intent.ACTION_SEND);
email.putExtra(Intent.EXTRA_SUBJECT,"Email Subject");
email.putExtra(Intent.EXTRA_TEXT, "email_body");//Share your call logs or sms data in the body
// need this to prompts email client only
email.setType("message/rfc822");
startActivity(Intent.createChooser(email, "Choose an Email client :"));

Related

Get Only Before 5 Minutes Inbox SMS

I want to select only latest inbox SMS on button click. Here is my code.
btnGet = (Button) findViewById(R.id.btnGet);
btnGet.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
if (fetchInbox() != null) {
ArrayList sms1 = fetchInbox();
for (int i = 0; i < sms1.size(); i++) {
String st = sms1.get(i).toString();
String[] sArr = st.split("\\$");
mobile = sArr[0];
sms = sArr[1];
useGet(mobile, sms);
}
} else {
textView1.setText("no sms");
}
} catch (Exception ex) {
textView1.setText("Exception" + ex.getMessage());
}
}
});
And here is my function to fetch SMS.
public ArrayList fetchInbox()
{
ArrayList sms = new ArrayList();
Uri uriSms = Uri.parse("content://sms/inbox");
Cursor cursor = getContentResolver().query(uriSms, new String[]{"_id", "address", "date", "body"},null,null,null);
cursor.moveToFirst();
while (cursor.moveToNext()) {
String id = cursor.getString(0);
String address = cursor.getString(1);
String body = cursor.getString(3);
sms.add(address + "$" + body + "$" + id);
}
return sms;
}
I am able get all inbox SMS by this code, but I want to select only before 5 minutes inbox SMS. I am new with android apps.
Cursor cursor = getContentResolver().query (Uri uri,
String[] projection,
String selection,
String[] selectionArgs,
String sortOrder)
selection : A filter declaring which rows to return. Passing null will
return all rows for the given URI.
As you can see, you can specifies the criteria for selecting rows.
First get the current date time.
Calendar date = Calendar.getInstance();
long t = date.getTimeInMillis();
Then subtract 5 mins from current time.
static final long ONE_MINUTE_IN_MILLIS = 60000;
Date afterSubtractingFiveMins = new Date(t - (5 * ONE_MINUTE_IN_MILLIS));
Now create the filter and query the messages.
String filter = "date>=" + afterSubtractingFiveMins.getTime();
Cursor cursor = getContentResolver().query(uriSms, new String[]{"_id", "address", "date", "body"},filter,null,null);
PS: I didn't check the code. You may have to optimize.

Android Call Log data between two dates and Total duration of calls from same number.

want to get the call log history by today, yesterday, last seven days and last 30days along with that i want to show the total duration of incoming and outgoing calls of that particular number.
suppose abc has 3 outgoing and 1 incoming calls. i should get the total duration of those calls.
just let me know if we can get duration and calls log by cursor GroupBy or ORDER BY clause rather than looping and adding duration. Just give me rough structure for better solution and can work effectively .
String[] whereValue=null;
Calendar calendar = Calendar.getInstance();
String currentDate = String.valueOf(calendar.getTimeInMillis());
switch (period) {
case DAY:
whereValue = new String[]{getTimeFrom(period),currentDate};
break;
case YESTERDAY:
whereValue = new String[]{getTimeFrom(period),currentDate};
break;
case WEEK:
whereValue = new String[]{getTimeFrom(period),currentDate};
break;
case MONTH:
whereValue = new String[]{getTimeFrom(period),currentDate};
break;
default:
Log.d(Utils.LOG_TAG, "Error:");
}
String strOrder = android.provider.CallLog.Calls.DATE + " DESC";
Uri callUri = Uri.parse("content://call_log/calls");
Cursor cur = context.getContentResolver().query(callUri, null, android.provider.CallLog.Calls.DATE+" BETWEEN ? AND ?", whereValue, strOrder);
String callNumber = cur.getString(cur
.getColumnIndex(android.provider.CallLog.Calls.NUMBER));
String callName = cur
.getString(cur
.getColumnIndex(android.provider.CallLog.Calls.CACHED_NAME));
String callType = cur.getString(cur
.getColumnIndex(android.provider.CallLog.Calls.TYPE));
String dir = null;
int dircode = Integer.parseInt(callType);
switch (dircode) {
case CallLog.Calls.OUTGOING_TYPE:
case CallLog.Calls.INCOMING_TYPE:
break;
}
String duration = cur.getString(cur
.getColumnIndex(android.provider.CallLog.Calls.DURATION));
the above code is even not working for getting call log between fromdate to till date. any help?
I have managed to get the call log between two dates. You can get call log of today, yesterday, last seven days, last 30days. as well duration of calls (calls from same number multiple times also)
you should pass selection as
android.provider.CallLog.Calls.DATE + " BETWEEN ? AND ?"
and
selectionArgs
whereValue = new String[]{String.valueOf(calendar1.getTimeInMillis()),String.valueOf(calendar.getTimeInMillis());};
Map<String, StatEntry> callLogMap1 = new HashMap<>();
callLogMap1.clear();
String strOrder1 = android.provider.CallLog.Calls.DATE + " DESC limit 500";
Uri callUri = Uri.parse("content://call_log/calls");
Cursor cur = getContentResolver().query(CallLog.Calls.CONTENT_URI, null, android.provider.CallLog.Calls.DATE + " BETWEEN ? AND ?", whereValue,
strOrder1);
if (cur != null) {
try {
while (cur.moveToNext()) {
String callNumber = cur.getString(cur.getColumnIndex(android.provider.CallLog.Calls.NUMBER));
// String callDate = cur.getString(cur.getColumnIndex(android.provider.CallLog.Calls.DATE));
int duration = cur.getInt(cur.getColumnIndex(android.provider.CallLog.Calls.DURATION));
String name = cur.getString(cur.getColumnIndex(CallLog.Calls.CACHED_NAME));
StatEntry StatEntry1 = null;
int id = cur.getInt(cur.getColumnIndex(CallLog.Calls._ID));
int type = cur.getInt(cur.getColumnIndex(CallLog.Calls.TYPE));
if (callNumber != null & duration > 0 && (type == 1 || type == 2)) {
int n = callNumber.length();
String lastDigits;
String number = callNumber.replaceAll(Pattern.quote("+"), ""); //replacing the plus
//am just checking last 5digitis and saving to map so that we can get same //number duration
if (n >= 5) {
try {
lastDigits = String.valueOf(Long.parseLong(number) % 100000);
} catch (NumberFormatException e) {
e.printStackTrace();
lastDigits = callNumber;
}
} else {
lastDigits = callNumber;
}
if (callLogMap1.containsKey(lastDigits)) {
StatEntry1 = callLogMap1.get(callNumber);
StatEntry1.setTitle(callNumber);
StatEntry1.Duration += duration;
} else {
StatEntry1 = new StatEntry();
StatEntry1.setTitle(callNumber);
StatEntry1.Duration += duration;
}
StatEntry1.setTime((StatEntry1.Duration) / 60);
callLogMap1.put(callNumber, StatEntry1);
}
}
} catch (Exception e) {
e.printStackTrace(
);
} finally {
cur.close();
}
}
atlast passing hashmap data to arraylist.
ArrayList<StatEntry> callLogList1 = new ArrayList<>(callLogMap1.size());
if (callLogMap1.size() > 0) {
for (Map.Entry<String, StatEntry> entry : callLogMap1.entrySet()) {
callLogList1.add(entry.getValue());
}
}
hope this will be helpful for viewers.
I managed to get the call log between two dates and also you can get the duration of the calls.Try this method..
public class CallLogActivity extends Activity {
TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_call_log);
textView = (TextView) findViewById(R.id.textCallBetween);
textView.setVisibility(View.GONE);
// listcallLog = (ListView) findViewById(R.id.calllogItems);
getCalldetails();
}
public void getCalldetails() {
StringBuffer stringBuffer = new StringBuffer();
String strOrder = android.provider.CallLog.Calls.DATE + " DESC";
Calendar calender = Calendar.getInstance();
calender.set(2016, calender.NOVEMBER, 18);
String fromDate = String.valueOf(calender.getTimeInMillis());
calender.set(2016, calender.NOVEMBER, 20);
String toDate = String.valueOf(calender.getTimeInMillis());
String[] whereValue = {fromDate,toDate};
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_CALL_LOG) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
Cursor managedCursor = getContentResolver().query(CallLog.Calls.CONTENT_URI, null, android.provider.CallLog.Calls.DATE + " BETWEEN ? AND ?", whereValue, strOrder);
// Cursor managedCursor = managedQuery(CallLog.Calls.CONTENT_URI, null, android.provider.CallLog.Calls.DATE, new String[]{" BETWEEN ? AND ?"}, strOrder);
int number = managedCursor.getColumnIndex(CallLog.Calls.NUMBER);
int type = managedCursor.getColumnIndex(CallLog.Calls.TYPE);
int date = managedCursor.getColumnIndex(CallLog.Calls.DATE);
int duration = managedCursor.getColumnIndex(CallLog.Calls.DURATION);
stringBuffer.append("Call Log :");
while (managedCursor.moveToNext())
{
String phoneNumber = managedCursor.getString(number);
String callType = managedCursor.getString(type);
String callDate = managedCursor.getString(date);
SimpleDateFormat formatter = new SimpleDateFormat(
"dd-MMM-yyyy HH:mm");
String dateString = formatter.format(new Date(Long
.parseLong(callDate)));
// Date callDayTime = new Date(Long.valueOf(callDate));
String callDuration = managedCursor.getString(duration);
String dir = null;
int dirCode = Integer.parseInt(callType);
switch (dirCode)
{
case CallLog.Calls.OUTGOING_TYPE :
dir = "OUTGOING";
break;
case CallLog.Calls.INCOMING_TYPE:
dir = "INCOMMING";
break;
case CallLog.Calls.MISSED_TYPE:
dir = "MISSED CALL";
break;
}
stringBuffer.append("\nPhone Number:--- " + phoneNumber + "\nCall Type:--- "
+ dir + "\nCall Date:---"
+ dateString + "\nCall Duration:---" + callDuration);
stringBuffer.append("\n--------------------------");
}
textView.setText(stringBuffer);
textView.setVisibility(View.VISIBLE);
}
}

Android how to get contact ID with my call log contact phone number

following is my code to read contact phone number from call log and i am calling the getContactID method to get contact id by passing phone number. That method must return ID of the contact which is saved in phone book.
public void getCallDetails()
{
#SuppressWarnings("deprecation")
String sortOrder = String.format("%s limit 100 ", CallLog.Calls.DATE + " DESC");
Cursor managedCursor = managedQuery( CallLog.Calls.CONTENT_URI, null, null, null, sortOrder);
int number = managedCursor.getColumnIndex( CallLog.Calls.NUMBER );
int type = managedCursor.getColumnIndex( CallLog.Calls.TYPE );
int date = managedCursor.getColumnIndex( CallLog.Calls.DATE);
int duration = managedCursor.getColumnIndex( CallLog.Calls.DURATION);
while (managedCursor.moveToNext())
{
phoneNumber = managedCursor.getString(number);
callType = managedCursor.getString(type);
callDate = managedCursor.getString(date);
contactName = getContactname(phoneNumber);
/**
* Hrer i am calling getContactID method to get contact id by passing phone number
*/
contactId = getContactId(phoneNumber);
//callDateTime = new Date(Long.valueOf(callDate));
long seconds=Long.parseLong(callDate);
SimpleDateFormat format1 = new SimpleDateFormat("dd-MM-yyyy hh:mm a");
callDateTime = format1.format(new Date(seconds));
callDuration = managedCursor.getString(duration);
String cType = null;
int cTypeCode = Integer.parseInt(callType);
switch(cTypeCode){
case CallLog.Calls.OUTGOING_TYPE:
cType = "OUTGOING";
break;
case CallLog.Calls.INCOMING_TYPE:
cType= "INCOMING";
break;
case CallLog.Calls.MISSED_TYPE:
cType = "MISSED";
break;
}
CallData calldata=new CallData(cType, phoneNumber, contactName, callDateTime, callDuration);
list.add(calldata);
}
// managedCursor.close();
}
/**
* This method gives the contact id of the saved contact
* #param phoneNumber2
* #return contact id
*/
private int getContactId(String phoneNumber2) {
// TODO Auto-generated method stub
return null;
}
/**
* this method is used to get the contact name by its phone number
* #param phoneNumber2
* #return contact name
*/
private String getContactname(String phoneNumber2) {
// TODO Auto-generated method stub
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;
}
And i dont know how to get contact ID from its phone number, any one help me!
/**
* Gets a list of contact ids that is pointed at the passed contact number
* parameter
*
* #param contactNo
* contact number whose contact Id is requested (no special chars)
* #param cxt
* application context
* #return String representation of a list of contact ids pointing to the
* contact in this format 'ID1','ID2','34','65','12','17'...
*/
public static String getContactRowIDLookupList(String contactNo, Context cxt) {
String contactNumber = Uri.encode(contactNo);
String contactIdList = new String();
if (contactNumber != null) {
Cursor contactLookupCursor = cxt.getContentResolver().query(
Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI,
Uri.encode(contactNumber)),
new String[] { PhoneLookup.DISPLAY_NAME, PhoneLookup._ID },
null, null, null);
if (contactLookupCursor != null) {
while (contactLookupCursor.moveToNext()) {
int phoneContactID = contactLookupCursor
.getInt(contactLookupCursor
.getColumnIndexOrThrow(PhoneLookup._ID));
if (phoneContactID > 0) {
contactIdList += "'" + phoneContactID + "',";
}
}
if (contactIdList.endsWith(",")) {
contactIdList = contactIdList.substring(0,
contactIdList.length() - 1);
}
}
contactLookupCursor.close();
}
return contactIdList;
}
If the phonebook has more than one contact saved with the same contact number, this method returns the id list. All you need to do is use this code and make sure the contact number you are passing to this method is digits only like "14085555555" not like "+1-408(555)-55-55" (no special chars)

arraylist is not updating correctly

I am using contentobserver to monitor SMS. It all works fine. When I try to save these SMS to a database, it shows an error error near "t" syntax error for a particular SMS. When I delete this particular SMS there is no problem. After installing, it shows all the messages correctly in order. But the error is sent to the end of my arraylist. Also the SMS sent from my phone after this are updated in between the list, not on the last position. Please help.
adapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1,list);
setListAdapter(adapter);
data = Incoming_outgoing_smsActivity.this.openOrCreateDatabase("Messages", MODE_PRIVATE, null);
data.execSQL("CREATE TABLE IF NOT EXISTS recor(text varchar(300));");
Cursor cur = data.rawQuery("SELECT * FROM recor", null);
while(cur.moveToNext()) {
String content = cur.getString(cur.getColumnIndex("text"));
backward_list.add(content);
list.add(content);
}
adapter.notifyDataSetChanged();
Cursor cursor = getContentResolver().query(Uri.parse("content://sms"), null, null, null, null);
while(cursor.moveToNext()) {
String number = cursor.getString(cursor.getColumnIndex("address"));
String[] projection = new String[] {ContactsContract.PhoneLookup.DISPLAY_NAME};
Uri contactUri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(number));
Cursor cursor_name = getContentResolver().query(contactUri, projection, null, null, null);
String body = cursor.getString(cursor.getColumnIndex("body"));
String type = cursor.getString(cursor.getColumnIndex("type"));
long date1= cursor.getLong(cursor.getColumnIndex("date"));
SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss.SSS");
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(date1);
try {
int n = cursor.getInt(cursor.getColumnIndex("type"));
switch (n) {
case 1:
String message = "FROM "+number+"\n"+formatter.format(calendar.getTime())+"\n"+"Message:-"+body;
if(backward_list.contains(message)) {
continue;
} else {
list.add(message);
backward_list.add(message);
data.execSQL("INSERT INTO recor VALUES('"+message+"')");
}
break;
case 2:
String messag = "TO "+number+"\n"+formatter.format(calendar.getTime())+"\n"+"Message:-"+body;
if(backward_list.contains(messag)) {
continue;
} else {
list.add(messag);
backward_list.add(messag);
data.execSQL("INSERT INTO recor VALUES('"+messag+"')");
}
break;
default:
break;
}
}
catch (Exception e) {
// TODO: handle exception
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
continue;
}
}
The above code saves the current SMS in your inbox to the database. The code below is used to update your inbox when a new SMS arrives. It does toast the arrived messages but doesn't insert them into the database.
data = Incoming_outgoing_smsActivity.this.openOrCreateDatabase("Messages", MODE_PRIVATE, null);
data.execSQL("CREATE TABLE IF NOT EXISTS recor(text varchar(300));");
super.onChange(selfChange);
Cursor cursor = getContentResolver().query(Uri.parse("content://sms"), null, null, null, null);
while(cursor.moveToNext()) {
String number = cursor.getString(cursor.getColumnIndex("address"));
String[] projection = new String[] {
ContactsContract.PhoneLookup.DISPLAY_NAME};
Uri contactUri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(number));
Cursor cursor_name = getContentResolver().query(contactUri, projection, null, null, null);
if(cursor_name.moveToFirst()) {
name = cursor_name.getString(cursor_name.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME));
}
String body = cursor.getString(cursor.getColumnIndex("body"));
String type = cursor.getString(cursor.getColumnIndex("type"));
long date1= cursor.getLong(cursor.getColumnIndex("date"));
SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss.SSS");
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(date1);
int n = cursor.getInt(cursor.getColumnIndex("type"));
switch (n) {
case 1:
String message = "FROM "+number+"\n"+formatter.format(calendar.getTime())+"\n"+"Message:-"+body;
if(backward_list.contains(message)) {
continue;
} else {
list.add(message);
backward_list.add(message);
data.execSQL("INSERT INTO recor VALUES('"+message+"')");
}
break;
case 2:
String messag = "TO "+number+"\n"+formatter.format(calendar.getTime())+"\n"+"Message:-"+body;
if(backward_list.contains(messag)) {
continue;
} else {
list.add(messag);
backward_list.add(messag);
data.execSQL("INSERT INTO recor VALUES('"+messag+"')");
}
break;
default:
break;
}
At a guess there was some sort of restricted character/word in the one SMS.
You should use prepared statements to take care of the issue.
See this SO Answer for an example.
For your second issue about the order of display, change/use an ORDER BY in your query to set the proper order.

MMS sender address problem

I am trying to get the address of the sender but I run into a little problem. If the person that sends the message is the first person in any of the conversations to send one, the query of the content://mms/inbox returns with zero rows?? but when someone sends any other mms message it will return back with the _id fine and i dont understand why the first one wont work right?
private String checkMmsMessages(Context context){
String address = "address";
Cursor curPdu = context.getContentResolver ().query(Uri.parse("content://mms/inbox"), null, null, null, null);
if(curPdu.moveToNext()){ //first MMS message curPdu.moveToNext() is false
String id = curPdu.getString (curPdu.getColumnIndex ("_id"));
Log.v("MMS", "ID1: " + id.toString());
Uri uriAddr = Uri.parse ("content://mms/" + id + "/addr");
Cursor curAddr = context.getContentResolver().query(uriAddr,null,"type=137",null,null);
if(curAddr.moveToNext()){
address = curAddr.getString (curAddr.getColumnIndex ("address"));
Log.v("MMS", "Address1: " + address.toString());
if(address.contentEquals("insert-address-token")){
Cursor curAddr2 = context.getContentResolver().query(uriAddr,null,"type=151", null,null);
if(curAddr2.moveToNext()){
address = curAddr2.getString(curAddr2.getColumnIndex("address"));
}
}
}
}
Log.v("MMS", address.toString());
return address;
}
Also something else that does not make sense is when when i have the phone plugged into the computer and step through the that section with the debugger, that problem does not happen and it gets the address every time.... it only happens when the phone is not connected, i just dont understand?
The problem was I was checking the database before the message was put into the database so I had to put a delay on the check
I think the issue is you are passing a value for selectionArgs instead of null to the query() method. I am not actually calling the mCursor's moveToNext() method in my code but instead I am implementing this logic in the getView() method of a SimpleCursorAdapter.
Uri uri = Uri.parse("content://mms-sms/conversations/" + mThreadId);
String[] projection = new String[] { "body", "person", "sub",
"subject", "retr_st", "type", "date", "ct_cls", "sub_cs",
"_id", "read", "ct_l", "st", "msg_box", "reply_path_present",
"m_cls", "read_status", "ct_t", "status", "retr_txt_cs",
"d_rpt", "error_code", "m_id", "date_sent", "m_type", "v",
"exp", "pri", "service_center", "address", "rr", "rpt_a",
"resp_txt", "locked", "resp_st", "m_size" };
String sortOrder = "normalized_date";
Cursor mCursor = getActivity().getContentResolver().query(uri,projection, null, null, sortOrder);
String messageAddress;
int type;
while (mCursor.moveToNext()) {
String messageId = mCursor.getString(mCursor.getColumnIndex("_id"));
Uri.Builder builder = Uri.parse("content://mms").buildUpon();
builder.appendPath(messageId).appendPath("addr");
Cursor c = mContext.getContentResolver().query(builder.build(), new String[] {
"*"
}, null, null, null);
while (c.moveToNext()) {
messageAddress = c.getString(c.getColumnIndex("address"));
if (!messageAddress.equals("insert-address-token")) {
type = c.getInt(c.getColumnIndex("type"));
c.moveToLast();
}
}
c.close();
}
try this...
private String getAddressNumber(String id) {
String selectionAdd = new String("msg_id=" + id);
String uriStr = MessageFormat.format("content://mms/{0}/addr", id);
Uri uriAddress = Uri.parse(uriStr);
Cursor cursor = getContentResolver().query(uriAddress, null, selectionAdd, null, null);
String phoneNum = null;
if (cursor.moveToFirst()) {
do {
String number = cursor.getString(cursor.getColumnIndex("address"));
if (number != null) {
boolean isNumberFormat = true;
try {
Long.parseLong(number.replace("-", ""));
phoneNum = number;
} catch (NumberFormatException e) { // ex) "insert-address-token"
// if (phoneNum == null) {
// phoneNum = number;
// }
isNumberFormat = false;
}
if (isNumberFormat)
break;
}
} while (cursor.moveToNext());
}
if (cursor != null) {
cursor.close();
}
return phoneNum;
}

Categories

Resources