How to get the SMS date from messenger? - android

Android default messenger sort SMS in several groups using received time(picture).
I am trying to show sms inbox in custom listview like default messenger using cursor:
// Create Inbox box URI
Uri inboxURI = Uri.parse( "content://sms/inbox" );
// List required columns
String[] reqCols = new String[]{"_id", "address", "body", "date"};
// Get Content Resolver object, which will deal with Content
// Provider
ContentResolver contentResolver = getContentResolver();
// Fetch Inbox SMS Message from Built-in Content Provider
Cursor cursor = contentResolver.query( inboxURI, reqCols, null, null,
null );
sms = new ArrayList<>();
String date = "";
cursor.moveToLast();
while (cursor.moveToPrevious() || cursor.isLast()) {
//to get phone number
address = cursor.getString( cursor.getColumnIndex( "address" ) );
//to get massage
body = cursor.getString( cursor.getColumnIndexOrThrow( "body" ) );
//to get date of sms
date = cursor.getString( cursor.getColumnIndexOrThrow( "date" ) );
Long timestamp = Long.parseLong( date );
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis( timestamp );
Date finalDate = calendar.getTime();
smsDate = finalDate.toString();
but it is not working like that.It's like "Sun Aug 12 07:13:13 .....". I want to show time same as default messenger. What is the solution?

In Sms tables, Dates are stored as INTEGER in milliseconds. so, use
long sms_time= cur.getLong(cur.getColumnIndexOrThrow("date")) on Cursor.
This is the time in milli on which the SMS was recieved. Now Get The Current Time In Milli Seconds.
long now = System.currentTimeMillis();//get Current Time
now Calculate M=Difference In Minutes:
long minutes=(now - sms_time)/(1000*60);
Source: https://stackoverflow.com/a/13138710/3155082

Related

Get and filter events from Google Calendar

In my android app, I have the code to write, update and delete events from/to calendars.
Now I want to get some events from a calendar but I don't know the event IDs. I want to filter events by title, description, or any other value.
How can I do that?
My code:
public static void getEvents(Activity mContext) {
Uri.Builder builder = Uri.parse("content://com.android.calendar/instances/when").buildUpon();
long now = new Date().getTime();
ContentUris.appendId(builder, now - DateUtils.DAY_IN_MILLIS * 10000);
ContentUris.appendId(builder, now + DateUtils.DAY_IN_MILLIS * 10000);
String selection = "((calendar_id = ?) AND (description LIKE ?))";
String[] selectionArgs = new String[] {""+id, "'%abc%'"};
Cursor eventCursor = contentResolver.query(builder.build(),
new String[] { "title", "begin", "end", "allDay", "description"},
selection, selectionArgs,
"startDay ASC, startMinute ASC");
while (eventCursor.moveToNext()) {
String eventTitle = eventCursor.getString(0);
String description = eventCursor.getString(4);
}
}
When I filter by calendar id only - it works and I get all the events in this calendar. When I try to add the "AND description = ? " - I get 0 events although I know there are events with the string in their description.
Calendar API has Freebusy query where you conduct a filter between dates using timeMin and timeMax.
Check this SO thread for actual code sample.
If you wanted to do a query based on your preferences (title,etc), you'd have to make your own custom implementation. You can try to fetch all the events first then make your own custom query on the response.

How can I get the sms body and extract the content from that?

I tried the following code,
Uri inboxURI = Uri.parse("content://sms/inbox");
// List required columns
String[] reqCols = new String[] { "_id", "address", "body", "date" };
ContentResolver cr = getContentResolver();
Calendar cal = Calendar.getInstance();
Long currentDate = cal.getTimeInMillis();
cal.add(Calendar.HOUR, -1);
Long lastDate = cal.getTimeInMillis();
String criteria = "date between '" + lastDate + "' and '" + currentDate + "'";
Cursor c = cr.query(inboxURI, reqCols, criteria, null, null);
adapter = new SimpleCursorAdapter(this, R.layout.row, c,new String[] { "body", "address", "date" }, new int[] {
R.id.lblMsg, R.id.lblNumber, R.id.lblDate });
lvMsg.setAdapter(adapter);
Here i'm getting the SMSes which are received in the past 1 hour.
I want to filter even more by the content so tried the following,
String criteria = "(body like '%spent%' or body like '%withdrawn%') " +
"and date between '" + lastDate + "' and '" + currentDate + "'";
Now i'm getting the appropriate SMSes. But i want to get the amount which was spent/withdrawn.
Eg: My SMS is as follows
Rs.350.50 was spent oun your Credit card on XXXXXX at XXXX. Avl bal: Rs.35200.05
Here I want to extract 350.50
So this how i want to take all the amount spent/withdrawn from each SMS.
How can I acheive this?
You can do something like this to get the amount. First get the index of integer from the string like this
String s = new String("xyz123");
Matcher matcher = Pattern.compile("\\d+").matcher(s);
matcher.find();
int i = Integer.valueOf(matcher.group());
Then after getting the index of first integer you can then run a loop checking if the next character is a digit or not. When you find first non digit character exit the loop. So now you have both start and end index of amount. Now you can easily use String.substring(int startIndex,int endIndex) method to find exact amount properly

retrieve actual sent time of an received sms in android

In the original SMS app of android i can check the details of a received sms and it wil show me the time and date it was sent by the sender and the time i received this message.
I am interested in the time difference between these 2
I can get the time i received the sms via this code. how can i extend this so that i also get the time it was sent?
Uri uri = Uri.parse("content://sms");
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
if (cursor.moveToFirst()) {
for (int i = 0; i < cursor.getCount(); i++) {
String body = cursor.getString(cursor.getColumnIndexOrThrow("body"))
.toString();
String number = cursor.getString(cursor.getColumnIndexOrThrow("address"))
.toString();
String date = cursor.getString(cursor.getColumnIndexOrThrow("date"))
.toString();
Date smsDayTime = new Date(Long.valueOf(date));
String type = cursor.getString(cursor.getColumnIndexOrThrow("type"))
.toString();

Reading sms received after a date

I'm trying to read all the sms I received after a date.
Here is the code:
Uri SMS_CONTENT_URI = Uri.parse("content://sms");
Uri SMS_INBOX_CONTENT_URI = Uri.withAppendedPath(SMS_CONTENT_URI, "inbox");
Cursor cursor = context.getContentResolver().query( SMS_INBOX_CONTENT_URI, new String[] { "_id" }, "date>=61291393200000", null, null);
//61291393200000 = 03/01/12
This returns me a empty cursor.
When I was executing this code:
Cursor cursor = context.getContentResolver().query( SMS_INBOX_CONTENT_URI, new String[] { "_id" }, "read=1", null, null);
Was returning me all the sms.
Somebody knows how to filter the sms by date?
I tried to execute in the send sms too, but had the same problem.
I use following code to retrieve sms messages after a particular date.
// First select the date shown by the datepicker.
// Here I am assuming that a DatePicker object is already created with id dpResult
// to select a particular date.
DatePicker datePicker = (DatePicker) findViewById(R.id.dpResult);
// Now create a SimpleDateFormat object.
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
// Add 1 in month as its 0 based indexing in datePicker but not in SimpleDateFormat
String selectedDate = datePicker.getYear() + "-" + (datePicker.getMonth() + 1) + "-" + datePicker.getDayOfMonth();
// Now create a start time for this date in order to setup the filter.
Date dateStart = formatter.parse(selectedDate + "T00:00:00");
// Now create the filter and query the messages.
String filter = "date>=" + dateStart.getTime();
final Uri SMS_INBOX = Uri.parse("content://sms/inbox");
Cursor cursor = getContentResolver().query(SMS_INBOX, null, filter, null, null);
while(cursor.moveToNext()) {
// Perform the required stuff here.
}
cursor.close();
Got above code snippet from http://realembed.blogspot.com/2013/11/retrieve-sms-message-on-particular-date.html
// Just pass time stamp as a third parameter in your cursor query . and you will get filtered date in ascending order.
refer below.
Cursor cursor = getContentResolver().query(Uri.parse("content://sms/inbox"),
new String[] { "address", "date", "body", },"date>=1535547019783",null,"date ASC");
if (cursor.moveToFirst()) { // must check the result to prevent exception
do {
String msgData = "";
for(int ati=0;ati<cursor.getColumnCount();ati++)
{
msgData = "" + cursor.getColumnName(ati) + ":" + cursor.getString(ati);
String date= cursor.getString(cursor.getColumnIndex("body"));
Log.e("DATA",date);
}
// use msgData
} while (cursor.moveToNext());
} else {
// empty box, no SMS
}
cursor.close();
}
Did you try "date>='61291393200000'"?
It seems like numeric value SQL statement needs a quote 'xxx'.

Android Event contentResolver query synchronize problem

I am using following code to pull the data from the core event calendar application to show in my app.
ContentResolver contentResolver = this.getContentResolver();
final Cursor cursor = contentResolver.query(Uri.parse("content://calendar/calendars"),(new String[] { "_id", "displayName", "selected" }),null, null, null);
HashSet<String> calendarIds = new HashSet<String>();
while (cursor.moveToNext()) {
String _id = cursor.getString(0);
String displayName = cursor.getString(1);
Boolean selected = !cursor.getString(2).equals("0");
calendarIds.add(_id);
}
for (String id : calendarIds) {
Uri.Builder builder = Uri.parse(
"content://calendar/instances/when").buildUpon();
Calendar calendar = Calendar.getInstance();
long now = calendar.getTimeInMillis();
ContentUris.appendId(builder, now
- ((DateUtils.DAY_IN_MILLIS) * 24));
ContentUris.appendId(builder, now
+ ((DateUtils.DAY_IN_MILLIS) * 24));
Cursor eventCursor = contentResolver.query(builder.build(),
new String[] { "title", "begin", "end", "allDay",
"description", "eventLocation", "dtstart",
"dtend", "eventStatus", "visibility",
"transparency", "hasAlarm" },
"Calendars._id=" + id, null,
"startDay ASC, startMinute ASC");
while (eventCursor.moveToNext()) {
if (eventCursor != null) {
String title = eventCursor.getString(0);
}
}
The code is working fine. But sometime if I add a event in the calendar and come back to app, it is not showing the new event. If i exit the app and again come back or change the tab, the new event is added to the list. What have to do solve the synchronize?
When you come back to your app after the calendar add occurs, onResume() gets called. Re-query the cursor there to cause your UI to update.
Also, you should look at the ContentObserver interface, which sets up a callback interface for being notified of changes (Say they show up on the device after a network sync while you haven't left your app at all.)
Finally, using a CursorAdapter to drive a ListView from your Cursor will set up a ContentObserver automatically and take care of a lot of the glue code you had to write to get this far. It's a much more automatic way of doing it.

Categories

Resources