how can count a fix date inbox sms in android - android

I am trying to develop a SMS counter app in which I want to count all SMS of the present date. i don't want to count total inbox SMS. I am using following code but not getting the exact result. It's counting total inbox SMS.
TextView view = new TextView(this);
Uri uriSMSURI = Uri.parse("content://sms/inbox");
Cursor cur = getContentResolver().query(uriSMSURI, null, null, null,null);
/*
int nsm = 0;
while(cur.moveToNext()){
nsm+= + cur.getCount();
}
*/
String sms = "";
while ( cur.moveToNext());{
// sms += "From :" + cur.getString(2) + " : " + cur.getString(11)+"\n";
// sms += cur.getString(2);
sms += "Total SMS in the INBOX : "+cur.getCount();
}
view.setText(sms);
setContentView(view);
I am a new learner. Thanks in advance.

If you are trying to count the number of sms received within the last 24h you may do something like this (not sure if this actually work because I didn't tested it, but you get the idea) :
Uri uriSMSURI = Uri.parse("content://sms/inbox");
long now = System.currentTimeMillis();
long last24 = now - 24*60*60*1000;//24h in millis
String[] selectionArgs = new String[]{Long.toString(last24);
String selection = "WHERE " + "date" + ">?";
Cursor cur = getContentResolver().query(uriSMSURI, null, selection, selectionArgs,null);
Then a simple cur.getCount() should get you the number of sms received.

Uri uriSMSURI = Uri.parse("content://sms/inbox");
long now = System.currentTimeMillis();
long last24 = now - 24*60*60*1000;//24h in millis
String[] selectionArgs = new String[]{Long.toString(last24)};
String selection = "date" + ">?";
String[] projection = new String[]{"date"};
Cursor cur = getContentResolver().query(uriSMSURI, projection, selection, selectionArgs,null);
String sms = String.valueOf(cur.getCount());
This is the Exact resul what i wanted thanks for giving me quick reply

Related

SMS content provider cursor empty

This is code for get SMS log in a period of selected date but it returns empty cursor:
long lFrom = login.getTime();
long lTo= logout.getTime();
String[] whereValue = {String.valueOf(lFrom),String.valueOf(lTo)};
Cursor cursor = this.getContentResolver().query(allMessages, new String[]{"date", "type", "address"},
Telephony.Sms.DATE + " BETWEEN ? AND ?", whereValue, null);

Reading last sms from a particular sender

Im building a app that is reading last sms from spec number (vb# 8888). Code is working great. I only have one prob. When i get a new sms from other number (vb# 7777)my code stops reading sms from (v#8888). if i delete the new sms from (7777) than my code strats working again. I'm using this to update a string in my app. Can someone help me
This is my code
Uri mSmsinboxQueryUri = Uri.parse("content://sms/inbox");
Cursor cursor1 = getContentResolver().query(mSmsinboxQueryUri, null, null, null, null);
String[] columns = new String[]{"address", "body"};
if(cursor1.moveToFirst()) {
String address = cursor1.getString(cursor1.getColumnIndex(columns[0]));
if address.equalsIgnoreCase("+597*******")) {
body = cursor1.getString(cursor1.getColumnIndex(columns[3]));
Koers = (TextView) findViewById(R.id.Koersdiedag);
Koers.setText(body);//body
Your code is just reading the most recent message in the inbox, whomever it's from. If you want the most recent message from that particular number, you can adjust your query to match the number, and limit the results to one record.
Uri mSmsinboxQueryUri = Uri.parse("content://sms/inbox");
String[] projection = {"address", "body"};
String phoneNumber = "+597*******";
Cursor cursor1 = getContentResolver().query(mSmsinboxQueryUri,
projection,
"address = ?",
new String[] {phoneNumber},
"date DESC LIMIT 1");
if (cursor1 != null && cursor1.moveToFirst()) {
body = cursor1.getString(cursor1.getColumnIndex("body"));
Koers = (TextView) findViewById(R.id.Koersdiedag);
Koers.setText(body);
}

Android getting sms conversation with name or address

I'm developing an SMS program and I want to get conversations.
I wrote the code below and it works fine, but I wonder if it could be more efficient
This is for geting conversation threads
Uri SMS_INBOX = Uri.parse("content://sms/conversations/");
Cursor c = getContentResolver().query(SMS_INBOX, null, null, null, "date desc");
startManagingCursor(c);
String[] count = new String[c.getCount()];
String[] snippet = new String[c.getCount()];
String[] thread_id = new String[c.getCount()];
c.moveToFirst();
for (int i = 0; i < c.getCount(); i++) {
count[i] = c.getString(c.getColumnIndexOrThrow("msg_count"))
.toString();
thread_id[i] = c.getString(c.getColumnIndexOrThrow("thread_id"))
.toString();
snippet[i] = c.getString(c.getColumnIndexOrThrow("snippet"))
.toString();
//Toast.makeText(getApplicationContext(), count[i] + " - " + thread_id[i]+" - "+snippet[i] , Toast.LENGTH_LONG).show();
c.moveToNext();
}
c.close();
for getting addresses according to conversation thread
for(int ad = 0; ad < thread_id.length ; ad++)
{
Uri uri = Uri.parse("content://sms/inbox");
String where = "thread_id="+thread_id[ad];
Cursor mycursor= getContentResolver().query(uri, null, where ,null,null);
startManagingCursor(mycursor);
String[] number = new String[mycursor.getCount()];
if(mycursor.moveToFirst()){
for(int i=0;i<mycursor.getCount();i++){
number[i]=mycursor.getString(mycursor.getColumnIndexOrThrow("address")).toString();
mycursor.moveToNext();
}
}
mycursor.close();
and finally checking the adresses (if in contact list) and adding to a list
for(int i =0 ; i < numaralar.length ;i++)
{
String a = numaralar[i].substring(0,1);
if(!a.equals("+")){ kisiismi = numaralar[i]; }
ContentResolver localContentResolver = getApplicationContext().getContentResolver();
Cursor contactLookupCursor =
localContentResolver.query(
Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI,
Uri.encode(numaralar[i])),
new String[] {PhoneLookup.DISPLAY_NAME, PhoneLookup._ID},
null,
null,
null);
try {
while(contactLookupCursor.moveToNext()){
String contactName = contactLookupCursor.getString(contactLookupCursor.getColumnIndexOrThrow(PhoneLookup.DISPLAY_NAME));
kisiismi = contactName;
}
}catch (Exception e) {
kisiismi = numaralar[i].toString();
}
finally {
//Toast.makeText(getApplicationContext(), ad + kisiismi + " " + count[ad], Toast.LENGTH_LONG).show();
myArr.add(kisiismi);
contactLookupCursor.close();
}
}
Are there any way to make this process easier?
Since it is a simple SQLite query and the Contact provider can be accessed in a similar way, you should try to get the job done in SQL by GROUPING via number, timestamp and maybe thrad_id and then matching the results to a query to the contact provider (also via SQLite)
The documentation holds a pretty good description of all available columns.
https://developer.android.com/reference/android/provider/ContactsContract.PhoneLookupColumns.html
From KitKat onwards, we have a specific Uri for this: content://mms-sms/messages/byphone. But before that, this is what we can come up with:
Set<Integer> conversationIds = new HashSet<Integer>();
String numbers = "+xxxxxxxxxx,+yyyyyyyyyy";
final String[] PROJECTION = { Sms._ID, Sms.THREAD_ID };
final String SELECTION = Sms.ADDRESS + " IN (" + numbers.replaceAll("[^,]+", "?") + ")";
final String[] selectionArgs = numbers.split(",");
Cursor cursor = context.getContentResolver().query(Sms.CONTENT_URI, PROJECTION, SELECTION, selectionArgs, null);
int threadColumn = cursor.getColumnIndexOrThrow(Sms.THREAD_ID);
while (cursor.moveToNext())
conversationIds.add(cursor.getInt(threadColumn));
cursor.close();
return conversationIds;
There is no easy way to do the same with MMS messages because they don't keep their address in the database, you have to query each and every one separately. If you need to do it repeatedly, a viable solution is to cache MMS-to-phone number relations in a database of your own.
You can then use the identifiers accumulated in conversationIds to query the individual conversations. Note that if you want to merge different coversations belonging to the same contact, you can reuse the same query selection pattern above with passing in all ids as IN (?,...,?) at once.

Android sms reading by number

I am working on a sms application. in my App I have to list all the convrsation .SO i use the following Uri.
content://mms-sms/conversations/
Its working fine.And the following is my code snippet.
Uri uri = Uri.parse("content://mms-sms/conversations/");
Cursor c= getContentResolver().query(uri, null, null ,null,null);
startManagingCursor(c);
if(c.moveToFirst()){
for(int i=0;i<c.getCount();i++){
body[i]= c.getString(c.getColumnIndexOrThrow("body")).toString();
number[i]=c.getString(c.getColumnIndexOrThrow("address")).toString();
c.moveToNext();
}
}
c.close();
for (int i = 0; i < body.length; i++) {
System.out.println("body ="+body[i]);
System.out.println("number ="+number[i]);
}
The number prints each conversations number and body prints the each conversations last message. But i want to get each conversations whole message and also help me to conversation for a specific number.
From Conversationscursor, You can get thread_id. Once you got thread_id, continue query from sms provider to return all message which has the same thread_id
Example : thread_id = 2
Uri SMS_INBOX = Uri.parse("content://sms");
Cursor c = getContentResolver().query(SMS_INBOX, null, "thread_id" + " = "
+ "2", null,
"date" + " ASC");
while (c.moveToNext()){
Log.v("BODY", c.getString(11).toString()); // 11 is the index of body with project URI
}

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'.

Categories

Resources