/SMSOnADate.java Secret
Last active
December 29, 2015 21:19
Android code snippet to retrieve all sms messages received on a particular date.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// First select the date shown by the datepicker. | |
// Here I am assumming that a DatePicker object is displayed on the view with id dpResult which is used | |
// 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. | |
String selectedDate = datePicker.getYear() + "-" + (datePicker.getMonth() + 1) + "-" + datePicker.getDayOfMonth(); | |
// Now create a start and end time for this date in order to setup the filter. | |
Date dateStart = formatter.parse(selectedDate + "T00:00:00"); | |
Date dateEnd = formatter.parse(selectedDate + "T23:59:59"); | |
// Now create the filter and query the messages. | |
String filter = "date>=" + dateStart.getTime() + " and date<=" + dateEnd.getTime(); | |
final Uri SMS_INBOX = Uri.parse("content://sms/inbox"); | |
Cursor cursor = getContentResolver().query(SMS_INBOX, null, filter, null, null); | |
List<String> items = new ArrayList<String>(); | |
while(cursor.moveToNext()) { | |
// Convert date to a readable format. | |
Calendar calendar = Calendar.getInstance(); | |
String date = cursor.getString(cursor.getColumnIndex("date")); | |
Long timestamp = Long.parseLong(date); | |
calendar.setTimeInMillis(timestamp); | |
Date finaldate = calendar.getTime(); | |
String smsDate = finaldate.toString(); | |
String smsBody = cursor.getString(cursor.getColumnIndex("body")); | |
String phoneNumber = " (" +cursor.getString(cursor.getColumnIndex("address")) + ") "; | |
items.add("From : " + Name + phoneNumber + "\n" + | |
"Date Sent: " + smsDate + "\n" + | |
"Message : " + smsBody + "\n"); | |
} | |
cursor.close(); | |
// items can be used to fill a ListView as shown below. | |
ListView smsList = (ListView)findViewById(R.id.smsList); | |
ListAdapter listAdapter= new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, android.R.id.text1, items); | |
smsList.setAdapter(listAdapter) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment