mitter.io
Search…
Start a Basic Chat
Let’s take this tutorial even further by building a simple chat UI and using Mitter.io to send/receive messages.

Build the basic layouts

Before we start handling data, we need a UI to show the outgoing/incoming data. Get started by adding some layouts for your chat bubbles and the chat RecyclerView.
To speed up this tutorial, just copy and paste the following pieces of code to your project. This is very basic Android stuff and we’ll not be diving deep into this part.
back_blue_rounded.xml
1
<?xml version="1.0" encoding="utf-8"?>
2
<shape xmlns:android="http://schemas.android.com/apk/res/android"
3
android:shape="rectangle">
4
5
<corners android:radius="50dp" />
6
<solid android:color="@color/colorPrimary" />
7
8
</shape>
Copied!
back_gray_rounded.xml
1
<?xml version="1.0" encoding="utf-8"?>
2
<shape xmlns:android="http://schemas.android.com/apk/res/android"
3
android:shape="rectangle">
4
5
<corners android:radius="50dp" />
6
<solid android:color="#EEEEEE" />
7
8
</shape>
Copied!
item_message_self.xml
1
<?xml version="1.0" encoding="utf-8"?>
2
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
3
xmlns:app="http://schemas.android.com/apk/res-auto"
4
xmlns:tools="http://schemas.android.com/tools"
5
android:layout_width="match_parent"
6
android:layout_height="wrap_content">
7
8
<android.support.v7.widget.AppCompatTextView
9
android:id="@+id/selfMessageText"
10
android:layout_width="wrap_content"
11
android:layout_height="wrap_content"
12
android:layout_margin="5dp"
13
android:background="@drawable/back_blue_rounded"
14
android:paddingBottom="10dp"
15
android:paddingEnd="20dp"
16
android:paddingStart="20dp"
17
android:paddingTop="10dp"
18
android:textColor="@android:color/white"
19
android:textSize="16sp"
20
app:layout_constraintBottom_toBottomOf="parent"
21
app:layout_constraintEnd_toEndOf="parent"
22
app:layout_constraintTop_toTopOf="parent"
23
tools:text="Hi, there!" />
24
25
</android.support.constraint.ConstraintLayout>
Copied!
item_message_other.xml
1
<?xml version="1.0" encoding="utf-8"?>
2
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
3
xmlns:app="http://schemas.android.com/apk/res-auto"
4
xmlns:tools="http://schemas.android.com/tools"
5
android:layout_width="match_parent"
6
android:layout_height="wrap_content">
7
8
<android.support.v7.widget.AppCompatTextView
9
android:id="@+id/otherMessageText"
10
android:layout_width="wrap_content"
11
android:layout_height="wrap_content"
12
android:layout_margin="5dp"
13
android:background="@drawable/back_gray_rounded"
14
android:padding="10dp"
15
android:paddingBottom="10dp"
16
android:paddingEnd="20dp"
17
android:paddingStart="20dp"
18
android:paddingTop="10dp"
19
android:textColor="@android:color/black"
20
android:textSize="16sp"
21
app:layout_constraintBottom_toBottomOf="parent"
22
app:layout_constraintStart_toStartOf="parent"
23
app:layout_constraintTop_toTopOf="parent"
24
tools:text="Hello!" />
25
26
</android.support.constraint.ConstraintLayout>
Copied!
So, you’ve added some basic layouts for rendering the chat bubbles. Now, let’s style the chat window. Open up your activity_main.xml layout file and add the following code:
activity_main.xml
1
<?xml version="1.0" encoding="utf-8"?>
2
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
3
xmlns:app="http://schemas.android.com/apk/res-auto"
4
xmlns:tools="http://schemas.android.com/tools"
5
android:layout_width="match_parent"
6
android:layout_height="match_parent"
7
android:background="@android:color/white"
8
tools:context=".MainActivity">
9
10
<android.support.v7.widget.RecyclerView
11
android:id="@+id/chatRecyclerView"
12
android:layout_width="0dp"
13
android:layout_height="0dp"
14
android:layout_marginBottom="10dp"
15
app:layout_constraintBottom_toBottomOf="parent"
16
app:layout_constraintBottom_toTopOf="@id/inputMessage"
17
app:layout_constraintEnd_toEndOf="parent"
18
app:layout_constraintStart_toStartOf="parent"
19
app:layout_constraintTop_toTopOf="parent" />
20
21
<View
22
android:layout_width="match_parent"
23
android:layout_height="1dp"
24
android:background="#EEEEEE"
25
app:layout_constraintTop_toBottomOf="@id/chatRecyclerView" />
26
27
<Button
28
android:id="@+id/sendButton"
29
style="@style/Base.Widget.AppCompat.Button.Borderless"
30
android:layout_width="wrap_content"
31
android:layout_height="wrap_content"
32
android:layout_marginBottom="5dp"
33
android:text="Send"
34
app:layout_constraintBottom_toBottomOf="parent"
35
app:layout_constraintEnd_toEndOf="parent" />
36
37
<android.support.v7.widget.AppCompatEditText
38
android:id="@+id/inputMessage"
39
android:layout_width="0dp"
40
android:layout_height="40dp"
41
android:layout_marginBottom="10dp"
42
android:layout_marginEnd="10dp"
43
android:layout_marginStart="20dp"
44
android:background="@android:color/white"
45
android:hint="Type your message"
46
android:inputType="textCapSentences"
47
android:textSize="16sp"
48
app:layout_constraintBottom_toBottomOf="parent"
49
app:layout_constraintEnd_toStartOf="@id/sendButton"
50
app:layout_constraintStart_toStartOf="parent" />
51
52
</android.support.constraint.ConstraintLayout>
Copied!

Prepare the adapter

Now that your layouts are in place, get started by adding an adapter for your RecyclerView.
Assuming you’ve named your adapter ChatRecyclerViewAdapter, your class should look something like this:
Kotlin
Java
ChatRecyclerViewAdapter.kt
1
class ChatRecyclerViewAdapter(
2
private val messageList: List<Message>,
3
private val currentUserId: String
4
) : RecyclerView.Adapter<ChatRecyclerViewAdapter.ViewHolder>() {
5
private val MESSAGE_SELF_VIEW = 0
6
private val MESSAGE_OTHER_VIEW = 1
7
8
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
9
val layoutId = if (viewType == MESSAGE_SELF_VIEW) R.layout.item_message_self else R.layout.item_message_other
10
val itemView = LayoutInflater.from(parent.context).inflate(layoutId, parent, false)
11
return ViewHolder(itemView)
12
}
13
14
override fun getItemCount(): Int = messageList.size
15
16
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
17
holder.bindMessage(messageList[position])
18
}
19
20
override fun getItemViewType(position: Int) = if (messageList[position].senderId.domainId() == currentUserId)
21
MESSAGE_SELF_VIEW else MESSAGE_OTHER_VIEW
22
23
inner class ViewHolder(itemView: View?) : RecyclerView.ViewHolder(itemView) {
24
fun bindMessage(message: Message) {
25
with(message) {
26
if (senderId.domainId() == currentUserId) {
27
itemView?.selfMessageText?.text = textPayload
28
} else {
29
itemView?.otherMessageText?.text = textPayload
30
}
31
}
32
}
33
}
34
}
Copied!
ChatRecyclerViewAdapter.java
1
public class ChatRecyclerViewAdapter extends RecyclerView.Adapter<ChatRecyclerViewAdapter.ViewHolder> {
2
private List<Message> messageList;
3
private String currentUserId;
4
5
private int MESSAGE_SELF_VIEW = 0;
6
private int MESSAGE_OTHER_VIEW = 1;
7
8
public ChatRecyclerViewAdapter(
9
List<Message> messageList,
10
String currentUserId
11
) {
12
this.messageList = messageList;
13
this.currentUserId = currentUserId;
14
}
15
16
@NonNull
17
@Override
18
public ChatRecyclerViewAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
19
int layoutId;
20
21
if (viewType == MESSAGE_SELF_VIEW) {
22
layoutId = R.layout.item_message_self;
23
} else {
24
layoutId = R.layout.item_message_other;
25
}
26
27
View itemView = LayoutInflater.from(parent.getContext()).inflate(layoutId, parent, false);
28
return new ViewHolder(itemView);
29
}
30
31
@Override
32
public void onBindViewHolder(@NonNull ChatRecyclerViewAdapter.ViewHolder holder, int position) {
33
Message message = messageList.get(position);
34
35
if (message.getSenderId().domainId().equals(currentUserId)) {
36
holder.selfMessageText.setText(message.getTextPayload());
37
} else {
38
holder.otherMessageText.setText(message.getTextPayload());
39
}
40
}
41
42
@Override
43
public int getItemCount() {
44
return messageList != null ? messageList.size() : 0;
45
}
46
47
@Override
48
public int getItemViewType(int position) {
49
if (messageList.get(position).getSenderId().domainId().equals(currentUserId)) {
50
return MESSAGE_SELF_VIEW;
51
} else {
52
return MESSAGE_OTHER_VIEW;
53
}
54
}
55
56
class ViewHolder extends RecyclerView.ViewHolder {
57
private TextView selfMessageText;
58
private TextView otherMessageText;
59
60
public ViewHolder(View itemView) {
61
super(itemView);
62
63
selfMessageText = (TextView) itemView.findViewById(R.id.selfMessageText);
64
otherMessageText = (TextView) itemView.findViewById(R.id.otherMessageText);
65
}
66
}
67
}
Copied!
Here, we receive a list of Message objects to display the chat items, and compare the senderId field to the currentUserId field to decide whether the bubble should render on the right or on the left.

Render messages in the window

The final step to rendering the messages in a channel to the screen is to wire up the ChatRecyclerViewAdapter that you created to the RecyclerView that you had already added to your layout.
Get started by initialising an empty list for holding the incoming Message objects and setting a layout manager for your RecyclerView.
Kotlin
Java
MainActivity.kt
1
class MainActivity : AppCompatActivity() {
2
3
private lateinit var mitter: Mitter
4
private val channelId: String = "6dedfac5-8060-4ad3-8d69-20a72fb86899"
5
6
private val messageList = mutableListOf<Message>()
7
private lateinit var chatRecyclerViewAdapter: ChatRecyclerViewAdapter
8
9
override fun onCreate(savedInstanceState: Bundle?) {
10
super.onCreate(savedInstanceState)
11
setContentView(R.layout.activity_main)
12
13
mitter = (application as MyApp).mitter
14
15
val users = mitter.Users()
16
val channels = mitter.Channels()
17
val messaging = mitter.Messaging()
18
19
chatRecyclerView.layoutManager = LinearLayoutManager(this)
20
}
21
}
Copied!
MainActivity.java
1
public class MainActivity extends AppCompatActivity {
2
private Mitter mitter;
3
private String channelId = "6dedfac5-8060-4ad3-8d69-20a72fb86899";
4
5
private RecyclerView chatRecyclerView;
6
private List<Message> messageList = new ArrayList<>();
7
private ChatRecyclerViewAdapter chatRecyclerViewAdapter;
8
9
@Override
10
protected void onCreate(@Nullable Bundle savedInstanceState) {
11
super.onCreate(savedInstanceState);
12
setContentView(R.layout.activity_main);
13
14
mitter = ((MyApp) getApplication()).mitter;
15
16
Mitter.Users users = mitter.new Users();
17
Mitter.Channels channels = mitter.new Channels();
18
Mitter.Messaging messaging = mitter.new Messaging();
19
20
chatRecyclerView = (RecyclerView) findViewById(R.id.chatRecyclerView);
21
chatRecyclerView.setLayoutManager(new LinearLayoutManager(this));
22
}
23
}
Copied!
Now, you need to make a call to fetch messages in the channel that you had already created.
If you’ve noticed, in the previous code snippet, the channel ID is already defined in the class. Replace the channel ID string with your actual channel ID over there.
Once that’s done, just make a call to the getMessagesInChannel() method on the Messaging object to get a list of messages in the channel:
Kotlin
Java
MainActivity.kt
1
messaging.getMessagesInChannel(
2
channelId = channelId,
3
onValueAvailableCallback = object : Mitter.OnValueAvailableCallback<List<Message>> {
4
override fun onError(apiError: ApiError) {
5
Log.d("MSA", "Error in getting messages")
6
}
7
8
override fun onValueAvailable(value: List<Message>) {
9
messageList.addAll(value)
10
chatRecyclerViewAdapter = ChatRecyclerViewAdapter(
11
messageList = messageList,
12
currentUserId = mitter.getUserId()
13
)
14
15
chatRecyclerView?.adapter = chatRecyclerViewAdapter
16
}
17
}
18
)
Copied!
MainActivity.java
1
messaging.getMessagesInChannel(
2
channelId,
3
new FetchMessageConfig(),
4
new Mitter.OnValueAvailableCallback<List<Message>>() {
5
@Override
6
public void onValueAvailable(List<Message> messages) {
7
messageList.addAll(messages);
8
chatRecyclerViewAdapter = new ChatRecyclerViewAdapter(
9
messageList,
10
mitter.getUserId()
11
);
12
13
chatRecyclerView.setAdapter(chatRecyclerViewAdapter);
14
}
15
16
@Override
17
public void onError(ApiError apiError) {
18
Log.d("MSA", "Error in getting messages");
19
}
20
}
21
);
Copied!
Here, we add the total incoming message list to our already defined empty message list. Next, we hook up that list with our ChatRecyclerViewAdapter and also retrieve the currently logged-in user ID and pass it to the adapter for the bubble alignment that we discussed previously.
The final step is to assign our ChatRecyclerViewAdapter object as the RecyclerView adapter to render the elements on the screen.
If you open up your app right now, it’ll display a blank screen because you haven’t sent any messages yet.
Basic chat window layout
Let’s do that now.

Send a basic text message

We’ve already added a basic EditText and a Button to our app while defining the layouts. Let’s connect them in the activity to send the typed text on the press of the Send button.
Kotlin
Java
MainActivity.kt
1
sendButton.setOnClickListener {
2
messaging.sendTextMessage(
3
channelId = channelId,
4
message = inputMessage?.text.toString(),
5
onValueUpdatedCallback = object : Mitter.OnValueUpdatedCallback {
6
override fun onError(apiError: ApiError) {}
7
8
override fun onSuccess() {
9
inputMessage?.text?.clear()
10
}
11
}
12
)
13
}
Copied!
MainActivity.java
1
sendButton.setOnClickListener(new View.OnClickListener() {
2
@Override
3
public void onClick(View v) {
4
messaging.sendTextMessage(
5
channelId,
6
inputMessage.getText().toString(),
7
new AppliedAclList(
8
new ArrayList<AppliedAcl>(),
9
new ArrayList<AppliedAcl>()
10
),
11
new Mitter.OnValueUpdatedCallback() {
12
@Override
13
public void onSuccess() {
14
inputMessage.getText().clear();
15
}
16
17
@Override
18
public void onError(ApiError apiError) { }
19
}
20
);
21
}
22
});
Copied!
Here, we’re listening to the click events on the Send button and sending a message by calling the sendTextMessage() method on the Messaging object. We pass the typed text to the method as the message text.
After the message has been sent successfully, we clear the input area. You can also show a progress bar while sending the message by utilising this callback.
That’s all wired in. You can test if this works by typing something in the input field and hitting Send.
Do note that you won’t see the message appear on the screen even after it’s sent successfully. This is because we haven’t hooked our push message listener with the UI.
We’ll do this in the next section. For now, after sending a message, just close and reopen the app to see the message populated on the screen.
Messages in the channel being populated in the chat window

Hook push messages with the UI

You can choose any way you want to pass around data from your Application class to your MainActivity. For this tutorial, we’ll stick to an event bus to do our job.
We’ll use Greenrobot’s EventBus 3 for this project. It’s pretty easy to use, while being reliable. Add the library to your project by including this line in your build.gradle:
build.gradle
1
implementation 'org.greenrobot:eventbus:3.1.1'
Copied!
Once that’s done, add a subscribing method in your MainActivity to listen to the incoming messages:
Kotlin
Java
MainActivity.kt
1
@Subscribe(threadMode = ThreadMode.MAIN)
2
fun onNewMessage(message: Message) {
3
messageList.add(message)
4
chatRecyclerViewAdapter.notifyItemInserted(messageList.size - 1)
5
}
Copied!
MainActivity.java
1
@Subscribe(threadMode = ThreadMode.MAIN)
2
public void onNewMessage(Message message) {
3
messageList.add(message);
4
chatRecyclerViewAdapter.notifyItemInserted(messageList.size() - 1);
5
}
Copied!
After that, you need to register your MainActivity to listen to any event bus events. Just modify your onCreate() to include this code:
Kotlin
Java
MainActivity.kt
1
EventBus.getDefault().register(this)
Copied!
MainActivity.java
1
EventBus.getDefault().register(this);
Copied!
Then, override the onDestroy() method to clean up any registered listeners:
Kotlin
Java
MainActivity.kt
1
override fun onDestroy() {
2
super.onDestroy()
3
4
if (EventBus.getDefault().isRegistered(this)) {
5
EventBus.getDefault().unregister(this)
6
}
7
}
Copied!
MainActivity.java
1
@Override
2
protected void onDestroy() {
3
super.onDestroy();
4
5
if (EventBus.getDefault().isRegistered(this)) {
6
EventBus.getDefault().unregister(this);
7
}
8
}
Copied!
Finally, navigate to your custom Application class, locate the previously registered push message listener and modify it to this:
Kotlin
Java
MyApp.kt
1
mitter.registerOnPushMessageReceivedListener(object : Mitter.OnPushMessageReceivedCallback {
2
override fun onChannelStreamData(
3
channelId: String,
4
streamId: String,
5
streamData: ContextFreeMessage
6
) {}
7
8
override fun onNewChannel(channel: Channel) {}
9
10
override fun onNewChannelTimelineEvent(
11
channelId: String,
12
timelineEvent: TimelineEvent
13
) {}
14
15
override fun onNewMessage(
16
channelId: String,
17
message: Message
18
) {
19
//Send the incoming message to the registered listener
20
EventBus.getDefault().post(message)
21
}
22
23
override fun onNewMessageTimelineEvent(
24
messageId: String,
25
timelineEvent: TimelineEvent
26
) {}
27
28
override fun onParticipationChangedEvent(
29
channelId: String,
30
participantId: String,
31
newStatus: ParticipationStatus,
32
oldStatus: ParticipationStatus?
33
) {}
34
})
Copied!
MyApp.java
1
mitter.registerOnPushMessageReceivedListener(new Mitter.OnPushMessageReceivedCallback() {
2
@Override
3
public void onNewMessage(
4
String channelId,
5
Message message
6
) {
7
//Send the incoming message to the registered listener
8
EventBus.getDefault().post(message);
9
}
10
11
@Override
12
public void onNewChannel(Channel channel) { }
13
14
@Override
15
public void onNewMessageTimelineEvent(
16
String messageId,
17
TimelineEvent timelineEvent
18
) { }
19
20
@Override
21
public void onNewChannelTimelineEvent(
22
String channelId,
23
TimelineEvent timelineEvent
24
) { }
25
26
@Override
27
public void onParticipationChangedEvent(
28
String channelId, String participantId,
29
ParticipationStatus participationStatus,
30
ParticipationStatus participationStatus1
31
) { }
32
33
@Override
34
public void onChannelStreamData(
35
String channelId,
36
String streamId,
37
ContextFreeMessage contextFreeMessage
38
) { }
39
});
Copied!
If you open up your app now and send a text message, you should be able to see it added to the list as soon as the message is sent.
Messages are being transferred in and out the app in real-time