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'.
Related
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
I want to write a query in android using contentResolver to get images of particular date only from gallery?
final String[] columns = { MediaStore.Images.Media.DATA, MediaStore.Images.Media._ID };
Cursor imagecursor = getApplicationContext().getContentResolver().query(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns, null,
null, null);
This gives me all the images,I want images of particular date and particular time.Please suggest.
You can not directly query image from date itself MediaStore understand timestamp only. so if you want an image of particular date you must first convert that date into timestamp like following.
//converting date to timestamp
public static long getTimeStamp(String calculatedDate) {
DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
Date date = null;
try {
date = formatter.parse(calculatedDate);
} catch (ParseException e) {
e.printStackTrace();
}
long output = 0;
if (date != null) {
output = date.getTime() / 1000L;
}
String str = Long.toString(output);
return Long.parseLong(str) * 1000;
}
you now need to query this with timestamp like following.here you need to pass two timestamp that match images greater than given date and less than next date. so you need exact output as you want.
cursor = activity.getContentResolver().query(android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI, new String[]{MediaStore.MediaColumns.DATA}, MediaStore.Images.Media.DATE_TAKEN + ">=? and " + MediaStore.Images.Media.DATE_TAKEN + "<=?", new String[]{"" + givendate_timestamp, "" + nextdate_timestamp}, MediaStore.Images.Media.DATE_TAKEN + " DESC");
try this
String[] columns = {MediaStore.Images.Media._ID, MediaStore.Images.ImageColumns.DATE_TAKEN};
String orderBy = MediaStore.Images.ImageColumns.DATE_TAKEN + " DESC";
for more How to make sort gallery thumbnails image by date
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.
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
i have an android application that use sqlite database and stored date under field name "match_date" in this format 2014-06-12.
what i want is to retrieve the stored dates then convert it to time Stamp to be able to compare it with the current date.
this is the chunk of code
public Cursor getAllRows(PendingIntent notificationIntent) throws ParseException {
String where = null;
c = database.query(true, TABLE_NAME, ALL_KEYS, where, null, null, null,
null, null);
if (c != null) {
c.moveToFirst();
// test for get current date and convert it to timeStamp
Log.e("time test","the current date in timeStamp =" + d1.getTime());
int index = c.getColumnIndex("match_date");
Date dateInGetAllRow = (Date)format.parse(c.getString(c.getColumnIndex("match_date")));
Log.e("inside the getAllRows", "first day is " + dateInGetAllRow.getTime());
Log.e("inside the Shownotification", "index is" + index);
///////////////////////////////////////////////////////////////////
while (!c.isAfterLast()) {
listdetail = new ItemDetails();
listdetail.setTeam1(c.getString(c.getColumnIndex("team1")));
listdetail.setTeam2(c.getString(c.getColumnIndex("team2")));
listdetail.setDate_match(c.getString(c
.getColumnIndex("match_date")));
NotificationCompat.Builder builder = new Builder(
getApplicationContext());
Notification notification = builder
.setSmallIcon(R.drawable.fifa_2014_4)
.setContentTitle("Up Comming Match")
.setContentText(
c.getString(c.getColumnIndex("match_date"))
+ (c.getColumnIndex("team1"))
+ (c.getColumnIndex("team2"))).build();
displayNotification(notification);
c.moveToNext();
}
}
return c;
}
hope that someone can help me i will appreciate this help.
I'm not not sure you mean this:
java.util.Date date= new java.util.Date();
Timestamp ts = Timestamp(date.getTime());