Как объединить все SMS-сообщения от отправителя в один в ListView, как в приложении обмена сообщениями по умолчанию? - PullRequest
0 голосов
/ 16 декабря 2011

У меня есть ListView, показывающий все входящие смс. Я хочу объединить все смс по номеру и просто показать количество смс, полученных этим отправителем, как в главном окне стандартного приложения обмена сообщениями.

Я использую список действий, который использует адаптер курсора, чтобы получить все сообщения, подобные этому:

public class MessageList extends ListActivity {

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        inboxcursor = getContentResolver().query(Uri.parse("content://sms/inbox"),new String [] {"person","address","body","date","_id","read", "status", "type", "reply_path_present", "subject","thread_id"} , null, null,"date DESC");
        smsadapter = new MessageListAdapter(this,inboxcursor);  
        getListView().setAdapter(smsadapter);
}

public class MessageListAdapter extends CursorAdapter {

        Context mcontext;
        LayoutInflater inflater;

        public MessageListAdapter(Context context, Cursor cursor) {
            super(context, cursor, true);

            inflater = LayoutInflater.from(context);
            mcontext = context;

        }

        @Override
        public void bindView(View view, Context context, Cursor cursor) {

             String number = cursor.getString(cursor.getColumnIndex("address"));
             TextView numbertext = (TextView) view.findViewById(R.id.number);
             numbertext.setText(number);

             String message = cursor.getString(cursor.getColumnIndex("body"));
             TextView messagetext = (TextView) view.findViewById(R.id.message);
             messagetext.setText(message);

        }

        @Override
        public View newView(Context context, Cursor cursor, ViewGroup parent) {

            View view = inflater.inflate(R.layout.listitems, null);

            return view;
            }

        }

Ответы [ 3 ]

1 голос
/ 16 декабря 2011

В своей деятельности создайте ArrayList<String, int>, в котором будут храниться данные, которые вы хотите отобразить.Строка - это номер смс отправителя, int - это количество.Затем запросите входящие сообщения:

cursor = getContentResolver().query(<sms table, assuming all are incoming. if not, you need to filter it on your where clause>, new String[] {sender column name}, null, null, null};

while(cursor.moveToNext()) {
  String sender = cursor.getString(cursor.getColumnName(<sender column name>));
  // check if the sender string exists in your arraylist. if not, create a new entry and set count to 1. else, get the position of the existing number and increment count by one.
};

, затем отправьте это в ListAdapter или ArrayAdapter.CursorAdapter не обрежет его.

0 голосов
/ 20 мая 2015

Сообщения с заданным номером имеют одинаковый идентификатор потока.Это может помочь вам в извлечении списка всех смс от того же пользователя.

0 голосов
/ 20 мая 2015

Я застрял в удалении дубликатов записи от того же пользователя в списке

public class SmsLogger extends Thread {

    private static final Uri SMS_URI = Uri.parse("content://sms");
    private static final String[] COLUMNS = new String[] {"date", "address", "body", "type"};
    private static final String WHERE = "type = 2";
    private static final String ORDER = "date DESC";

    private Context context;
   // private SharedPreferences prefs;
    private TelephonyManager tm;
   // private long timeLastChecked;
    private boolean roaming;
    Date afterdate,beforeDate;
    int j=1;
    public static  ArrayList<SmsDetailsPojo> arrDetailsSms;
   // private ArrayList<SmsDetailsPojo> arrContactNumber;
    private   boolean isFromDetailsFrag=false;
    //private  boolean isDataPushing=false;
    private AppData appData;

    String address;
    public SmsLogger(Context context,Date afterdate,Date beforeDate,boolean isFromDetailsFrag) {
        this.context = context;
        tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        this.afterdate=afterdate;
        this.beforeDate=beforeDate;
        this.isFromDetailsFrag=isFromDetailsFrag;
        arrDetailsSms=new ArrayList<SmsDetailsPojo>();
        appData=new AppData(context);
    }


    @Override
    public void run() {
        arrDetailsSms.clear();
        Logger.d("STARTED: OutSmsLogger");
      //  timeLastChecked = prefs.getLong(This.KEY_TIME_LAST_CHECKED_OUT_SMS, This.DEFAULT_LONG);
        final String SELECT = CallLog.Calls.DATE + ">=?" + " AND "
                + CallLog.Calls.DATE + "<?";
        Cursor cursor = context.getContentResolver().query(SMS_URI, COLUMNS,
                 SELECT,
                new String[] { String.valueOf(afterdate.getTime()),
                        String.valueOf(beforeDate.getTime()) },
              CallLog.Calls.DATE + " desc");
        Set<SmsLogData> smsLogsIncoming = null;
        Set<SmsLogData> smsLogsOutGoing = null;

        long date;
        String  body, simNumber;
        SmsLogData outSmsLog;
        if (cursor.moveToNext()) {
            smsLogsIncoming = new HashSet<SmsLogData>();
            smsLogsOutGoing = new HashSet<SmsLogData>();
           // timeLastChecked = cursor.getLong(cursor.getColumnIndex("date"));
            simNumber = tm.getLine1Number();
            do {
                date = cursor.getLong(cursor.getColumnIndex("date"));
                address = cursor.getString(cursor.getColumnIndex("address"));
                body = cursor.getString(cursor.getColumnIndex("body"));
                String type = cursor.getString(cursor.getColumnIndex("type"));


                final SmsDetailsPojo dataItem=new SmsDetailsPojo();
                String contactName=Util.getContactName(context, address );
                dataItem.setContactNum(address);
                dataItem.setContactName(contactName);
                dataItem.setSmsCount(""+j);

                Util.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {

                        arrDetailsSms.add(dataItem);
                        arrDetailsSms = (ArrayList<SmsDetailsPojo>) arrContactNumber.clone();

                        // Iterate
                        for (int i = 0; i < arrContactNumber.size(); i++) {
                            for (int j = arrContactNumber.size() - 1; j >= i; j--) {
                                // If i is j, then it's the same object and don't need to be compared.
                                if (i == j) {
                                    continue;
                                }
                                // If the compared objects are equal, remove them from the copy and break
                                // to the next loop
                                if (arrContactNumber.get(i).getContactNum().equals(arrContactNumber.get(j).getContactNum())) {
                                    arrDetailsSms.remove(arrContactNumber.get(i));
                                    arrContactNumber.get(i).setSmsCount(""+(Integer.parseInt( arrContactNumber.get(i).getSmsCount().trim())+1));

                                    break;
                                }
                            }
                        }


                    }
               });
                //}

                switch (type) {
                case "1":

                     outSmsLog = new SmsLogData("", AppData.TYPE_OUT_SMS,
                             address, simNumber, date, body.length(), roaming);
                     if (smsLogsIncoming.contains(outSmsLog)) {
                         continue;
                     }
                     smsLogsIncoming.add(outSmsLog);
                   // Log.e("logtag", "call dur"+callDuration+"call sum"+sumOutgoing);
                   // tvEndDate.setText(""+sum);
                    break;

                case "2":

                     outSmsLog = new SmsLogData("", AppData.TYPE_OUT_SMS,
                             address, simNumber, date, body.length(), roaming);
                     if (smsLogsIncoming.contains(outSmsLog)) {
                         continue;
                     }
                     smsLogsOutGoing.add(outSmsLog);

                    break;


            }   






            } while (cursor.moveToNext());
        }

        cursor.close();
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...