mitter.io
  • Welcome
  • Migrating from cloud to on-prem
  • Get mitter.io
    • Custom configuration
  • Getting started
    • Build Your First Android App
      • Setup
      • Authenticate a User
      • Start a Basic Chat
      • Selective Deliveries
      • Custom Payloads
    • Build Your First iOS App
      • Overview
      • Installation
      • Basic Setup
      • Receive Push Messages
      • Storyboard
      • Channel List
      • Channel Window
    • Build Your First Web App
      • Setting Up Your App
      • Start a Basic Chat
      • Selective Deliveries
    • Build Your First React Native app
  • Platform Reference
    • Introduction
    • Concepts
    • Authorization and Access
    • Calling the APIs
    • Users
    • Channels
      • Channel Streams and Typing Indicators
    • Messages
    • Delivery Endpoints (Push Notifications)
    • Federated Authentication
    • Basic Permissions and Privileges
    • ACLs and Advanced Permission Model
    • Metadata
  • SDKs
    • Android
      • Getting Started
      • Set up FCM
      • Presence and Timeline Events
      • Profiles, Pagination and Locators
      • Using the UI Framework
    • iOS
      • Installation
      • Basic Setup
      • Get the current user details
      • Create a Channel
      • Messaging
      • Push Messages
    • Javascript
      • Using the UI framework (web only)
      • For react-native
      • For node.js
      • TSDocs / JSDocs
      • For Typescript Users
    • Java (Backend)
Powered by GitBook
On this page
  • Schedule meetings on chat
  • Add the DatePickerDialog
  • Send a message with the picked date
  • Show the date message bubbles
  • Add action to the chat bubble buttons
  1. Getting started
  2. Build Your First Android App

Custom Payloads

Learn how to add actions & extra information to your messages and build a playful and engaging chat experience.

In the previous chapter, we learnt how to send messages to specific people in a group chat with ACLs.

In this chapter, we’ll see how to take the demo app one step further by adding some custom payloads to our outgoing messages.

Schedule meetings on chat

To demonstrate the power and use of custom payloads, we’ll be letting our users schedule meetings on our app. The basic workflow is as follows:

  • Pick a date while sending a message

  • Receivers confirm their availability with a Yes/No action

Add the DatePickerDialog

We’ll use the standard DatePickerDialog to render a calendar dialog on the screen and allow the user to pick a date from the displayed calendar.

Get started by adding a button to the chat screen. For this example, you can use this vector drawable as the calendar button. Just copy this code to your project under the drawable package:

Now, navigate to your activity_main.xml and modify the code to look similar to this:

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/white"
    tools:context=".MainActivity">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/chatRecyclerView"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginBottom="10dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintBottom_toTopOf="@id/inputMessage"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <View
        android:id="@+id/divider"
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:background="@color/colorGray"
        app:layout_constraintTop_toBottomOf="@id/chatRecyclerView" />

    <Button
        android:id="@+id/sendButton"
        style="@style/Base.Widget.AppCompat.Button.Borderless"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="5dp"
        android:text="Send"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent" />

    <ImageView
        android:id="@+id/pickDateButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_date_range_black_24dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toStartOf="@id/sendButton"
        app:layout_constraintTop_toBottomOf="@id/divider" />

    <android.support.v7.widget.AppCompatEditText
        android:id="@+id/inputMessage"
        android:layout_width="0dp"
        android:layout_height="40dp"
        android:layout_marginBottom="10dp"
        android:layout_marginEnd="10dp"
        android:layout_marginStart="20dp"
        android:background="@android:color/white"
        android:hint="Type your message"
        android:inputType="textCapSentences"
        android:textSize="16sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toStartOf="@id/pickDateButton"
        app:layout_constraintStart_toStartOf="parent" />

</android.support.constraint.ConstraintLayout>

If you compare this file to your previously created layout, you’ll see that we’ve just added an ImageView showing up the calendar icon that we added in the previous step and adjusted the surrounding views to accommodate this icon.

Lastly, go to your MainActivity and add the listener for this button to open up the DatePickerDialog and listen for inputs from the user.

Define an instance variable in your MainActivity to hold the picked date:

MainActivity.kt
private var pickedDate: String = ""
MainActivity.java
private String pickedDate = ""

Then, add this block of code inside your onCreate() method:

MainActivity.kt
pickDateButton?.setOnClickListener {
        val calendar = Calendar.getInstance()
        val year = calendar.get(Calendar.YEAR)
        val month = calendar.get(Calendar.MONTH)
        val day = calendar.get(Calendar.DAY_OF_MONTH)

        val datePickerDialog = DatePickerDialog(
            this,
            { _, year, month, day ->
                pickedDate = "$day/${month + 1}/$year"
            },
            year,
            month,
            day
        )

        datePickerDialog.show()
}
MainActivity.java
pickDateButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Calendar calendar = Calendar.getInstance();
        final int year = calendar.get(Calendar.YEAR);
        final int month = calendar.get(Calendar.MONTH);
        final int day = calendar.get(Calendar.DAY_OF_MONTH);

        DatePickerDialog datePickerDialog = new DatePickerDialog(
            MainActivity.this,
            new DatePickerDialog.OnDateSetListener() {
                @Override
                public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                    pickedDate = dayOfMonth + "/" + (month + 1) + "/" + year;
                }
            },
            year,
            month,
            day
        );

        datePickerDialog.show();
    }
});

Note: To use the DatePickerDialog you need to have your minSdkVersion set to 24 or above

Send a message with the picked date

Now that we’ve added the functionality to capture a date from the user, we can send it along with our message to be used by our RecyclerView to render messages differently.

Get started by adding a new data class (or a POJO, if using Java) to hold the picked date:

PickedDate.kt
@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY)
data class PickedDate(
    @JsonProperty("date") val date: String
)
PickedDate.java
@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY)
public class PickedDate {
    @JsonProperty("date")
    String date;

    public PickedDate() {
    }

    public PickedDate(String date) {
        this.date = date;
    }

    public String getDate() {
        return date;
    }

    public void setDate(String date) {
        this.date = date;
    }

    @Override
    public String toString() {
        return "PickedDate{" +
            "date='" + date + '\'' +
            '}';
    }
}

Now, go to MainActivity and inside the sendButton.setOnClickListener {} block (or inside the onClick() method, if using Java) , modify your code to this:

MainActivity.kt
if (pickedDate.isEmpty()) {
        messaging.sendTextMessage(
            channelId = channelId,
            message = typedInput,
            appliedAcls = appliedAcls,
            onValueUpdatedCallback = object : Mitter.OnValueUpdatedCallback {
                override fun onError(apiError: ApiError) {}

                override fun onSuccess() {
                    inputMessage?.text?.clear()
                }
            }
        )
} else {
       val objectMapper = ObjectMapper()
       val sender = IdUtils.of<User>(mitter.getUserId())

       val pickedDate = PickedDate(this.pickedDate)

       val timelineEvent = TimelineEvent(
            eventId = UUID.randomUUID().toString(),
            type = StandardTimelineEventTypeNames.Messages.SentTime,
            eventTimeMs = System.currentTimeMillis(),
            subject = sender
       )

        val message = Message(
            messageId = UUID.randomUUID().toString(),
            senderId = sender,
            textPayload = typedInput,
            timelineEvents = listOf(timelineEvent),
            appliedAcls = appliedAcls,
            messageData = listOf(
                MessageDatum(
                    "io.mitter.android.messages.DateMessage",
                    objectMapper.valueToTree(pickedDate)
                )
            )
        )

        messaging.sendMessage(
            channelId = channelId,
            message = message,
            onValueUpdatedCallback = object : Mitter.OnValueUpdatedCallback {
                override fun onError(apiError: ApiError) {

                }

                override fun onSuccess() {
                    inputMessage?.text?.clear()
                    this@MainActivity.pickedDate = ""
                }
            }
        )
}
MainActivity.java
if (pickedDate.isEmpty()) {
    messaging.sendTextMessage(
        channelId,
        typedInput,
        appliedAcls,
        new Mitter.OnValueUpdatedCallback() {
            @Override
            public void onSuccess() {
                inputMessage.getText().clear();
            }

            @Override
            public void onError(ApiError apiError) {
            }
        }
    );
} else {
    ObjectMapper objectMapper = new ObjectMapper();
    Identifiable<User> sender = IdUtils.of(mitter.getUserId(), User.class);

    PickedDate date = new PickedDate(pickedDate);

    TimelineEvent timelineEvent = new TimelineEvent(
        UUID.randomUUID().toString(),
        "",
        StandardTimelineEventTypeNames.Messages.SentTime,
        System.currentTimeMillis(),
        sender,
        null
    );

    List<TimelineEvent> timelineEvents = new ArrayList<>();
    timelineEvents.add(timelineEvent);

    MessageDatum messageDatum = new MessageDatum(
        "io.mitter.android.messages.DateMessage",
        objectMapper.valueToTree(date)
    );

    List<MessageDatum> messageData = new ArrayList<>();
    messageData.add(messageDatum);

    Message message = new Message(
        UUID.randomUUID().toString(),
        "",
        StandardMessageType.Standard,
        StandardPayloadTypeNames.TextMessage,
        sender,
        typedInput,
        messageData,
        timelineEvents,
        appliedAcls,
        new EntityMetadata(),
        null
    );

    messaging.sendMessage(
        channelId,
        message,
        new Mitter.OnValueUpdatedCallback() {
            @Override
            public void onSuccess() {
                inputMessage.getText().clear();
                pickedDate = "";
            }

            @Override
            public void onError(ApiError apiError) {

            }
        }
    );
}

What we did here is:

  • Wrapped our previous sendTextMessage() method inside an if-else block

  • Wrapped the picked date string inside a PickedDate object ready to be serialised

  • Constructed a SentTime timeline event for our Message object

  • Constructed a Message object with all the previous params and a new MessageDatum list

A MessageDatum is a single unit of your custom payload. It has a unique ID to identify the type of payload you’re sending and also the payload in serialised form.

Now, if you type a message in the input field and tap on the calendar icon you’ll see a date picker pop-up. Select a date and then hit Send.

The app will send out a message with the selected date as its payload.

We’ll make use of this payload in the next section where we’ll show a different chat bubble with this date information.

Show the date message bubbles

To make use of the custom payload that we attached to our message, we need to add some custom layouts for our chat bubbles to accommodate the attached date.

Get started by adding these two layouts to your project:

item_message_date_self.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <android.support.constraint.ConstraintLayout
        android:id="@+id/messageContainer"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/back_blue_rounded"
        app:layout_constraintEnd_toEndOf="parent">

        <android.support.v7.widget.AppCompatTextView
            android:id="@+id/selfDateMessageText"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="5dp"
            android:paddingBottom="5dp"
            android:paddingEnd="20dp"
            android:paddingStart="20dp"
            android:paddingTop="10dp"
            android:textColor="@android:color/white"
            android:textSize="16sp"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            tools:text="Can we have a meeting?" />

        <android.support.v7.widget.AppCompatTextView
            android:id="@+id/selfDate"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:paddingBottom="15dp"
            android:paddingEnd="20dp"
            android:paddingStart="20dp"
            android:textColor="#eee"
            android:textSize="12sp"
            android:textStyle="italic"
            app:layout_constraintStart_toStartOf="@id/selfDateMessageText"
            app:layout_constraintTop_toBottomOf="@id/selfDateMessageText"
            tools:text="On: 26/09/2018" />

    </android.support.constraint.ConstraintLayout>

</android.support.constraint.ConstraintLayout>
item_message_date.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <android.support.constraint.ConstraintLayout
        android:id="@+id/messageContainer"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/back_gray_rounded">

        <android.support.v7.widget.AppCompatTextView
            android:id="@+id/dateMessageText"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="5dp"
            android:paddingBottom="5dp"
            android:paddingEnd="20dp"
            android:paddingStart="20dp"
            android:paddingTop="10dp"
            android:textColor="@android:color/black"
            android:textSize="16sp"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            tools:text="Can we have a meeting?" />

        <android.support.v7.widget.AppCompatTextView
            android:id="@+id/date"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:paddingBottom="15dp"
            android:paddingEnd="20dp"
            android:paddingStart="20dp"
            android:textSize="12sp"
            android:textStyle="italic"
            app:layout_constraintStart_toStartOf="@id/dateMessageText"
            app:layout_constraintTop_toBottomOf="@id/dateMessageText"
            tools:text="On: 26/09/2018" />

    </android.support.constraint.ConstraintLayout>

    <Button
        android:id="@+id/yesButton"
        style="@style/Base.Widget.AppCompat.Button.Borderless"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Yes"
        app:layout_constraintTop_toBottomOf="@id/messageContainer" />

    <Button
        android:id="@+id/noButton"
        style="@style/Base.Widget.AppCompat.Button.Borderless"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="No"
        app:layout_constraintStart_toEndOf="@id/yesButton"
        app:layout_constraintTop_toBottomOf="@id/messageContainer" />

</android.support.constraint.ConstraintLayout>

After you’ve added these, the next step is to modify your ChatRecyclerViewAdapter to something like this:

ChatRecyclerViewAdapter.kt
class ChatRecyclerViewAdapter(
    private val messageList: List<Message>,
    private val currentUserId: String
) : RecyclerView.Adapter<ChatRecyclerViewAdapter.ViewHolder>() {
    private val objectMapper = ObjectMapper()

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val itemView = LayoutInflater.from(parent.context).inflate(getLayoutId(viewType), parent, false)
        return ViewHolder(itemView)
    }

    override fun getItemCount(): Int = messageList.size

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        holder.bindMessage(messageList[position], holder.itemViewType)
    }

    override fun getItemViewType(position: Int): Int = when (messageList[position].senderId.domainId()) {
        currentUserId -> {
            val message = messageList[position]

            if (message.messageData.isEmpty()) {
                MessageTypes.SELF_PLAIN_MESSAGE
            } else {
                MessageTypes.SELF_DATE_MESSAGE
            }
        }
        else -> {
            val message = messageList[position]

            if (message.messageData.isEmpty()) {
                MessageTypes.OTHER_PLAIN_MESSAGE
            } else {
                MessageTypes.OTHER_DATE_MESSAGE
            }
        }
    }

    object MessageTypes {
        const val SELF_PLAIN_MESSAGE = 0
        const val OTHER_PLAIN_MESSAGE = 1
        const val SELF_DATE_MESSAGE = 2
        const val OTHER_DATE_MESSAGE = 3
    }

    private fun getLayoutId(viewType: Int): Int = when (viewType) {
        MessageTypes.SELF_PLAIN_MESSAGE -> R.layout.item_message_self
        MessageTypes.SELF_DATE_MESSAGE -> R.layout.item_message_date_self
        MessageTypes.OTHER_DATE_MESSAGE -> R.layout.item_message_date
        else -> R.layout.item_message_other
    }

    inner class ViewHolder(itemView: View?) : RecyclerView.ViewHolder(itemView) {
        fun bindMessage(message: Message, viewType: Int) {
            with(message) {
                when (viewType) {
                    MessageTypes.SELF_PLAIN_MESSAGE -> {
                        itemView?.selfMessageText?.text = textPayload
                    }
                    MessageTypes.OTHER_PLAIN_MESSAGE -> {
                        itemView?.otherMessageText?.text = textPayload
                    }
                    MessageTypes.SELF_DATE_MESSAGE -> {
                        val pickedDate = objectMapper.treeToValue(messageData[0].data, PickedDate::class.java)
                        itemView?.selfDateMessageText?.text = textPayload
                        itemView?.selfDate?.text = "On: ${pickedDate.date}"
                    }
                    MessageTypes.OTHER_DATE_MESSAGE -> {
                        val pickedDate = objectMapper.treeToValue(messageData[0].data, PickedDate::class.java)
                        itemView?.dateMessageText?.text = textPayload
                        itemView?.date?.text = "On: ${pickedDate.date}"
                    }
                }
            }
        }
    }
}
ChatRecyclerViewAdapter.java
public class ChatRecyclerViewAdapter extends RecyclerView.Adapter<ChatRecyclerViewAdapter.ViewHolder> {
    private List<Message> messageList;
    private String currentUserId;

    private ObjectMapper objectMapper = new ObjectMapper();

    public ChatRecyclerViewAdapter(
        List<Message> messageList,
        String currentUserId
    ) {
        this.messageList = messageList;
        this.currentUserId = currentUserId;
    }

    @NonNull
    @Override
    public ChatRecyclerViewAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(parent.getContext()).inflate(
            getLayoutId(viewType),
            parent,
            false
        );
        return new ViewHolder(itemView, viewType);
    }

    @Override
    public void onBindViewHolder(@NonNull ChatRecyclerViewAdapter.ViewHolder holder, int position) {
        Message message = messageList.get(position);
        PickedDate pickedDate = null;

        if (!message.getMessageData().isEmpty() && message.getMessageData().get(0).getData() != null) {
            try {
                pickedDate = objectMapper.treeToValue(message.getMessageData().get(0).getData(), PickedDate.class);
            } catch (JsonProcessingException jpe) {
            }
        }

        switch (holder.getItemViewType()) {
            case MessageTypes.SELF_PLAIN_MESSAGE:
                holder.selfMessageText.setText(message.getTextPayload());
                break;
            case MessageTypes.OTHER_PLAIN_MESSAGE:
                holder.otherMessageText.setText(message.getTextPayload());
                break;
            case MessageTypes.SELF_DATE_MESSAGE:
                holder.selfDateMessageText.setText(message.getTextPayload());
                holder.selfDate.setText("On: " + pickedDate != null ? pickedDate.getDate() : "");
                break;
            case MessageTypes.OTHER_DATE_MESSAGE:
                holder.dateMessageText.setText(message.getTextPayload());
                holder.date.setText("On: " + pickedDate != null ? pickedDate.getDate() : "");
                break;
            default:
                break;
        }
    }

    @Override
    public int getItemCount() {
        return messageList != null ? messageList.size() : 0;
    }

    @Override
    public int getItemViewType(int position) {
        if (messageList.get(position).getSenderId().domainId().equals(currentUserId)) {
            Message message = messageList.get(position);

            if (message.getMessageData().isEmpty()) {
                return MessageTypes.SELF_PLAIN_MESSAGE;
            } else {
                return MessageTypes.SELF_DATE_MESSAGE;
            }
        } else {
            Message message = messageList.get(position);

            if (message.getMessageData().isEmpty()) {
                return MessageTypes.OTHER_PLAIN_MESSAGE;
            } else {
                return MessageTypes.OTHER_DATE_MESSAGE;
            }
        }
    }

    class MessageTypes {
        static final int SELF_PLAIN_MESSAGE = 0;
        static final int OTHER_PLAIN_MESSAGE = 1;
        static final int SELF_DATE_MESSAGE = 2;
        static final int OTHER_DATE_MESSAGE = 3;
    }

    private int getLayoutId(int viewType) {
        switch (viewType) {
            case MessageTypes.SELF_PLAIN_MESSAGE:
                return R.layout.item_message_self;
            case MessageTypes.SELF_DATE_MESSAGE:
                return R.layout.item_message_date_self;
            case MessageTypes.OTHER_DATE_MESSAGE:
                return R.layout.item_message_date;
            default:
                return R.layout.item_message_other;

        }
    }

    class ViewHolder extends RecyclerView.ViewHolder {
        private TextView selfMessageText;
        private TextView otherMessageText;
        private TextView selfDateMessageText;
        private TextView selfDate;
        private TextView dateMessageText;
        private TextView date;


        public ViewHolder(View itemView, int viewType) {
            super(itemView);

            switch (viewType) {
                case MessageTypes.SELF_PLAIN_MESSAGE:
                    selfMessageText = itemView.findViewById(R.id.selfMessageText);
                    break;
                case MessageTypes.OTHER_PLAIN_MESSAGE:
                    otherMessageText = itemView.findViewById(R.id.otherMessageText);
                    break;
                case MessageTypes.SELF_DATE_MESSAGE:
                    selfDateMessageText = itemView.findViewById(R.id.selfDateMessageText);
                    selfDate = itemView.findViewById(R.id.selfDate);
                    break;
                case MessageTypes.OTHER_DATE_MESSAGE:
                    dateMessageText = itemView.findViewById(R.id.dateMessageText);
                    date = itemView.findViewById(R.id.date);
                    break;
                default:
                    break;
            }
        }
    }
}

Here, we did a couple of things:

  • Added our new date message layouts

  • Mapped them to their specific message types

  • Rendered each message based on their message type or rather view type

If you run the app now and send a message with a date, you’ll see the date appearing right below your typed message text. Also, your date messages will appear different for different users:

  • Just the message text and the date for self-messages

  • Additional Yes/No buttons for other users’ messages

Go ahead, try this out.

Add action to the chat bubble buttons

The only thing that’s left in this chapter is to add some actions to the buttons that we added in the previous step.

First, create two empty classes called YesAction and NoAction. These are basically events that we’ll be sending out on the button clicks and act on them when we receive them in the MainActivity.

After you’ve done that, navigate to the ChatRecyclerViewAdapter and modify the following block inside your ViewHolder class like this:

ChatRecyclerViewAdapter.kt
MessageTypes.OTHER_DATE_MESSAGE -> {
        val pickedDate = objectMapper.treeToValue(messageData[0].data, PickedDate::class.java)
        itemView?.dateMessageText?.text = textPayload
        itemView?.date?.text = "On: ${pickedDate.date}"

        itemView?.yesButton?.setOnClickListener {
            EventBus.getDefault().post(YesAction())
        }

        itemView?.noButton?.setOnClickListener {
            EventBus.getDefault().post(NoAction())
        }
}
ChatRecyclerViewAdapter.java
case MessageTypes.OTHER_DATE_MESSAGE:
    dateMessageText = itemView.findViewById(R.id.dateMessageText);
    yesButton = itemView.findViewById(R.id.yesButton);
    noButton = itemView.findViewById(R.id.noButton);
    date = itemView.findViewById(R.id.date);

    yesButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            EventBus.getDefault().post(new YesAction());
        }
    });

    noButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            EventBus.getDefault().post(new NoAction());
        }
    });

    break;

Here, we’re basically sending out events using the event bus that we previously added to our app, on each button click.

Now, we need to subscribe to these sent events and act on them in our MainActivity. Navigate to your MainActivity and add the following methods:

MainActivity.kt
@Subscribe(threadMode = ThreadMode.MAIN)
fun onYesAction(yesAction: YesAction) {
   messaging.sendTextMessage(
        channelId = channelId,
        message = "Yes, I'm available"
    )
}

@Subscribe(threadMode = ThreadMode.MAIN)
fun onNoAction(noAction: NoAction) {
    messaging.sendTextMessage(
        channelId = channelId,
        message = "No, I'm not available"
    )
}
MainActivity.java
@Subscribe(threadMode = ThreadMode.MAIN)
public void onYesAction(YesAction yesAction) {
    messaging.sendTextMessage(
        channelId,
        "Yes, I'm available",
        new AppliedAclList(
            new ArrayList<AppliedAcl>(),
            new ArrayList<AppliedAcl>()
        ),
        null
    );
}

@Subscribe(threadMode = ThreadMode.MAIN)
public void onNoAction(NoAction noAction) {
    messaging.sendTextMessage(
        channelId,
        "No, I'm not available",
        new AppliedAclList(
            new ArrayList<AppliedAcl>(),
            new ArrayList<AppliedAcl>()
        ),
        null
    );
}

What we’re doing here is listening to the incoming YesAction and NoAction events and sending out a plain text message accordingly.

This will act as a shortcut confirmation message action for our users, kind of like what you see in popular apps like Google Allo and Facebook Messenger.

And that’s the end of the chapter. You’ve successfully added custom payloads to your messages and responded to them accordingly to update your UI.

PreviousSelective DeliveriesNextBuild Your First iOS App

Last updated 6 years ago

Choosing a date for the meeting using the built-in date picker dialog
The date message received with Yes/No options
Sending out a confirmation message on choosing an action