Simple Messenger

After this tutorial, you’ll be able to build an app just like this one:

ezgif-com-optimize

Before going into the action, make sure you have a working project that is set up to use Back4App’s Live Query API. You can check out the link below to the Live Query guide:

Live Query

In this project, we will create a simple app that will work as a message exchange client. Follow the steps and check out the source code by the end of the page.

Step 1 – Create Message class

We have to create a class named Message in the Parse Dashboard with the fields content, sender and message. The result is shown in the picture:

screenshot1

Also, don’t forget to follow the steps described on the Live Query article. After that, you are all set on the backend. Now to the app.

Step 2 – Create the Project

At Android Studio, create a new Project, as shown below:

screenshot4

Select the form factors shown in the picture below:

screenshot5

Select the Basic Activity model:

screenshot3

And name it MessageBoardActivity:

screenshot6

Now it is time to add elements to the app.

Step 3 – Add elements to the App

As soon as you open the project, go to the res folder and find the layout folder. In there, find the “activity_message_board.xml” file and double click it to open the part of the layout. Note that the template starts with a FloatingActionButton named “fab”. Lets first rename this button, by clicking once on its name on the Component Tree:

screenshot7

And then change its ID to “send”, shown in the pictures below:

screenshot9

Now, we have to add the elements to the app. On this very same layout, add a RelativeLayout to the existing CoordinatorLayout, and then add a PlainText to the just created Layout. The Component Tree should be like this:

screenshot10

Change the ID of the PlainText just added to “message” and change its “hint” field to “Type your message” and leave its “text” field blank. Also, make its “singleLine” field ticked(true) and its “inputType” to “textShortMessage”. All these adjustments can be done in the Properties tab, as shown:

screenshot11

Align the “message” element with the “send” button and you’re set in this file. Now, head to the file named “content_message_board.xml” and double click to open it.

You’ll see another part of the layout. This layout will be included in that one that was modified before – automatically, as soon as the app display its content. Let’s first change the ID of the TextView that is already in the RelativeLayout existing to “messageBoard”.

Then, leave blank its “text” field and check the field “layout_alignParentBottom”, which will allow you to resize the text field to a wanted size, which you ought to do. In this example, the field “layout_marginBottom” was set to “50 dp” giving it a nice size – this option is inside the “Layout_Margin” options.

Also, you’ll need to set the field “gravity” to “bottom”, so that the text comes from bottom to top and it is necessary to set the field “maxLines” to “20”, so that as soon as the chat is full it does not go over the “message” or the “send” elements. Below is an image with some of the properties that have been set:

screenshot13

Now, we just need to note that there is also a layout for the small menu that appears on the top right corner – the settings menu. There is nothing to be done in this layout, but to know that its ID is “action_settings”. It is necessary to program every element that has been changed or added to the layouts.

Step 4 – Add the working code to App

Every piece of code that does some functionality here should be added inside the “onCreate” method, in the MessageBoardActivity. First, let’s declare the elements we will use:

// Elements we are going to use
FloatingActionButton sendButton = (FloatingActionButton) findViewById(R.id.send);
final TextView messageBoard = (TextView) findViewById(R.id.messageBoard);
messageBoard.setMovementMethod(new ScrollingMovementMethod());
final EditText message = (EditText) findViewById(R.id.message);

Now, we have to add the initialization of the Back4App’s Parse API, which can be seen in the Live Query Tutorial. Next, we have to subscribe to the channel and add the text to the “messageBoard” as soon as it is created:

// Subscription being made that receives every message
final Subscription sub = new BaseQuery.Builder("Message")
        .where("type", "message")
        .addField("sender")
        .addField("content")
        .addField("type")
        .build()
        .subscribe();

// If a message is created, we add to the text field
sub.on(LiveQueryEvent.CREATE, new OnListener() {
    @Override
    public void on(JSONObject object) {
        try {
            String message = (String) ((JSONObject) object.get("object")).get("content");
            String sender = (String) ((JSONObject) object.get("object")).get("sender");
            String toBeAdded = sender + ": " + message;

            final String updatedText = '\n' + toBeAdded;

            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    messageBoard.append(updatedText);
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
});

Then, we have to add functionality to the “send” button. First, we need to create a String field named “sender”, which in this example has a default value of “Back4User” in this very same class that we are adding the functionality. Then, we ought to add the following code so that as soon as it is clicked, the message should be sent:

// Implementing the actions that our app will have
// Starting with the sendButton functionality
sendButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(final View view) {
        String messageToSend = message.getText().toString();

        Log.i("Message", "created correctly, "+messageToSend);

        //Creating and sending the message
        ParseObject click = new ParseObject("Message");
        click.put("content", messageToSend);
        click.put("sender", sender);
        click.put("type", "message");
        click.saveInBackground(new SaveCallback() {
            @Override
            public void done(ParseException e) {
                Log.i("Message", "Sent correctly");
            }
        });

        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                //Setting the text blank again
                message.setText("");
            }
        });
    }
});

Next element to be configured is the Settings button – the “action_settings” element. The design of this sort of menu is such that it has its own methods to fire menu options. Hence, it is imperative to modify its own methods, which in this case is the “onOptionsItemSelected”. Locate an “if” statement that has the following condition:

if (id == R.id.action_settings) {
    ...
}

And add the following code inside it:

//Creates a 
final EditText txtUrl = new EditText(this);

new AlertDialog.Builder(this)
        .setTitle("Settings")
        .setMessage("Please write the username you want")
        .setView(txtUrl)
        .setPositiveButton("Change username", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
                //Sets the sender
                sender = txtUrl.getText().toString();
            }
        })
        .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
            }
        })
        .show();

So, in this app we used Live Query capabilities to create a minimalistic messenger for Android. We created the classes at Back4App that were used to send the messages. Then, we set up the Android project using a nice template that Google offers with Android Studio. After that, we added and personalized the elements of the app (buttons, text fields and layouts). Finally, we added the code that sends the message to the button that exists in the layout; added some code to the settings menu, so that the name of the sender could be changed and added some code to receive messages.

And that’s it for this app. Check out the full code below:

https://github.com/rvitorper/back4app-messenger