Reading The Last 5 SMS Received From A Particular Number On A Particular Date
I am wondering how to read last five SMS received from a particular mobile number on a particular date. I know how to read all SMS from a particular sender, and how to read the las
Solution 1:
You're only seeing one message because your code is only handling the first record in the returned Cursor
. You need to loop over the Cursor
to handle the rest. For example:
if (cursor != null && cursor.moveToFirst()) {
do {
body = cursor1.getString(cursor1.getColumnIndex("body"));
totalBody = totalBody + body;
Log.d("Registration", totalBody);
} while (cursor.moveToNext());
}
Also, if you want to restrict the query to one day, you can use a Calendar
to figure the starting and ending times for that day in milliseconds - as that is how dates are stored in the SMS table - and add the appropriate comparison to the where
clause. For example:
private static final int DAY_MILLISECONDS = 24 * 60 * 60 * 1000;
private static final Uri inboxUri = Uri.parse("content://sms/inbox");
// Months are zero-based; i.e., JANUARY == 0
// Phone number must be exact in this example
private void listMessages(String phoneNumber, int year, int month, int day) {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, year);
cal.set(Calendar.MONTH, month);
cal.set(Calendar.DATE, day);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
String[] projection = {"address", "body"};
String whereAddress = "address = ?";
String whereDate = "date BETWEEN " + cal.getTimeInMillis() +
" AND " + (cal.getTimeInMillis() + DAY_MILLISECONDS);
String where = DatabaseUtils.concatenateWhere(whereAddress, whereDate);
Cursor cursor = null;
try {
cursor = getContentResolver().query(inboxUri,
projection,
where,
new String[]{phoneNumber},
"date DESC LIMIT 5");
if (cursor != null && cursor.moveToFirst()) {
do {
Log.d("Message", cursor.getString(cursor.getColumnIndex("body")));
} while (cursor.moveToNext());
}
}
catch (Exception e) {
e.printStackTrace();
}
finally {
if (cursor != null) {
cursor.close();
}
}
}
Post a Comment for "Reading The Last 5 SMS Received From A Particular Number On A Particular Date"