Search code examples
androidandroid-contentprovider

Android SMS: group by its thread id


I am implementing a SMS App, till now i achieved to get all the messages(sent, received, drafts) with its contact number, thread id, contact id, date, type.

Here is my code:

Uri mSmsinboxQueryUri = Uri.parse("content://sms");
        Cursor cursor = _context.getContentResolver().query(
                mSmsinboxQueryUri,
                new String[] { "_id", "thread_id", "address", "date", "body",
                        "type" }, null, null, null);

        String[] columns = new String[] { "address", "thread_id", "date",
                "body", "type" };
        if (cursor.getCount() > 0) {

            while (cursor.moveToNext()) {

                String address = null, date = null, msg = null, type = null, threadId = null;

                address = cursor.getString(cursor.getColumnIndex(columns[0]));
                threadId = cursor.getString(cursor.getColumnIndex(columns[1]));
                date = cursor.getString(cursor.getColumnIndex(columns[2]));
                msg = cursor.getString(cursor.getColumnIndex(columns[3]));
                type = cursor.getString(cursor.getColumnIndex(columns[4]));

                Log.e("SMS-inbox", "\nTHREAD_ID: "
                        + threadId + "\nNUMBER: " + address + "\nTIME: " + date + "\nMESSAGE: " + msg + "\nTYPE: " + type);
            }
        }
    }

Now, I need to separate these messages by thread id (messages with same thread id). How can I best achieve that? Thanks!


Solution

  • I would not save those strings seperatly in the first place.

    What I would do is a class like:

    public class SmsMsg {
        private String address = null;
        private String threadId = null;
        private String date = null;
        private String msg = null;
        private String type = null;
    
        //c'tor
        public SmsMsg(Cursor cursor) {
           this.address = cursor.getString(cursor.getColumnIndex("address"));
           this.threadId = cursor.getString(cursor.getColumnIndex("thread_id"));
           this.date = cursor.getString(cursor.getColumnIndex("date"));
           this.msg = cursor.getString(cursor.getColumnIndex("body"));
           this.type = cursor.getString(cursor.getColumnIndex("type")); 
        }
    }
    

    now you can instantiate an object of SmsMsg in your while-loop as long cursor.moveToNext() is true and add it to a List of your choice.

    You now could copy all messages of a desired threadId to a different List and sort it by date for example. That depends on what you want do do with it.