Home > Software design >  Unable to fetch unread messages from SMS inbox
Unable to fetch unread messages from SMS inbox

Time:08-18

I have successfully retrieved all messages from inbox but I want only unread messages . I have also apply in the query as read=0 which gives unread SMS but it can't retrive unread messages it retrieves all messages.

    public ArrayList<Message> fetchInboxSms(int type)  {
        ArrayList<Message> smsInbox = new ArrayList<Message>();
          Uri uriSms = Uri.parse("content://sms");
        SimpleDateFormat formatter1 = new SimpleDateFormat("dd/MM/yyyy");
        Calendar calendar2 = Calendar.getInstance();
        calendar2.setTimeInMillis(System.currentTimeMillis()-ONE_DAYS_MILIS);
        Date finaldate2 = calendar2.getTime();
        String date3 = formatter1.format(finaldate2);

        @SuppressLint("Recycle") Cursor cursor = this.getContentResolver()
                .query(uriSms,
                        new String[] { "_id", "address", "date", "body",
                                "type", " read = 0 " }, "type="   type, null,
                        "date"   " COLLATE LOCALIZED ASC");

        if (cursor != null) {
            cursor.moveToLast();
            if (cursor.getCount() > 0) {

                do {
                    Message message = new Message();
                  message.messageNumber = cursor.getString(cursor
                            .getColumnIndex("address"));
                     //message.messageContent = cursor.getString(cursor.getColumnIndex("date"));
                    String date =  cursor.getString(cursor.getColumnIndex("date"));
                    String content = cursor.getString(cursor.getColumnIndex("body"));             
                     
                    message.messageContent = content;
                     
                      smsInbox.add(message);
                } while (cursor.moveToPrevious());
            }
        }

        return smsInbox;

    }

CodePudding user response:

Change your query arguments like this

Cursor cursor = this.getContentResolver()
            .query(uriSms,
                new String[]{"_id", "address", "date", "body",
                    "type"}, " read = 0 AND type = "   type, null,
                "date"   " COLLATE LOCALIZED ASC");

You are passing selection where clause for read = 0 in projections instead of where clause.

This is how you can pass multiple where/selection clause.

  • Related