How do I get the count of SMS messages per contact into a textview?

10,666

Solution 1

Uri SMS_INBOX = Uri.parse("content://sms/conversations/");

Cursor c = getContentResolver().query(SMS_INBOX, null, null, null, null);

    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();
        Log.v("count", count[i]);
        Log.v("thread", thread_id[i]);
        Log.v("snippet", snippet[i]);
        c.moveToNext();
    }

See log and problem solved. Dont repost the same question : How do I display the count of text messages received from a contact?

Solution 2

I would perhaps add count(person) AS cnt to the columns String array and then I would add person as the groupBy argument to the query method.

EDIT:

And as pointed out by Jens, the GROUP BY paradigm isn't supported by the messaging ContentProvider.

What you could do is to create an in-memory database of your own at application startup (http://www.sqlite.org/inmemorydb.html) and copy-paste (query-insert) messages of interest from the system messaging database into your in-memory database. (NOTE! That this might fall out wrong if you are low on memory and have a tremendous amount of messages you're interested in). Since you'd be God in the in-memory database you could query it as you see fit with any exotic SQL querys you'd like...

Share:
10,666
Admin
Author by

Admin

Updated on June 04, 2022

Comments

  • Admin
    Admin over 1 year

    I have a listview that displays the contacts on my device. What I'm trying to do is display the number of text messages my device has received from each contact into a textview within my listview. I have only been able to display the total number of text messages within my inbox from this code:

            // gets total count of messages in inbox
            String folder = "content://sms/inbox";
            Uri mSmsQueryUri = Uri.parse(folder);
            String columns[] = new String[] {"person", "address", "body", "date","status"}; 
            String sortOrder = "date ASC"; 
            Cursor c = context.getContentResolver().query(mSmsQueryUri, columns, null, null, sortOrder);
    
            textview.setText(c.getCount());
    

    The problem with the above code is that for every row in my listview, this only shows the total. How can I split the total number between to it's corresponding contact?

    The end result is like this if I had 100 messages in my inbox: Contacts:

    Foo Manchuu: 25

    Bar Bee: 15

    Sna Fuu: 10

    John Doe: 50