Search code examples
javaandroidlistviewsmsandroid-cursoradapter

Add new received/send message to listview Android


I'm making an android app to send and receive text messages. But I can't show new incoming messages in my ListView.

Here is the code that I use to populate the ListView:

ListView lv = (ListView) view.findViewById(R.id.lvConversations);
Cursor c = getActivity().getContentResolver().query(INBOX_URI, projection, "address = '" + address + "'", null, "date");
ConversationCursorAdapter adap = new ConversationCursorAdapter(getActivity(),c);
lv.setAdapter(adap);
lv.setSelection(lv.getCount() - 1);

And here is my ConversationCursorAdapter

public class ConversationCursorAdapter extends CursorAdapter {

public ConversationCursorAdapter(Context context, Cursor c) {
    super(context, c, 0);
}

@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
    return LayoutInflater.from(context).inflate(R.layout.msg, parent, false);
}

@Override
public void bindView(View view, Context context, Cursor cursor) {
    TextView tvBody = (TextView) view.findViewById(R.id.tvBody);
    TextView tvDate = (TextView) view.findViewById(R.id.tvDate);
    String body = cursor.getString(cursor.getColumnIndexOrThrow("body"));
    Long date = cursor.getLong(cursor.getColumnIndexOrThrow("date"));
    tvBody.setText(body);
    tvDate.setText(date.toString());

}}

I also have a listener to get the new messages, but let's first concentrate on the sending messages. When the user clicks on the sendbutton the message is send, but doesn't show in the listview. Here is the code to send the message.

Button btnSend = (Button) view.findViewById(R.id.btnSend);
    btnSend.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            EditText et = (EditText) getView().findViewById(R.id.etSendMessage);
            SmsManager manager = SmsManager.getDefault() ;
            manager.sendTextMessage(toAddress, null, body, null, null);
            et.setText("");
        }
    });

Could somebody tell me what I'm doing wrong? Thank you!


Solution

  • First create broadcast receiver with some unique action like String ACTION = "message.received";

    use this action string as intent filter action string

    then notifiy that broadcast receiver when you are getting new data while API.

    then add new row to list view then you can archive by notifyDataSetChanged();