Build a location feed app for Android with Kotlin

Written by codebeast_ | Published 2018/07/02
Tech Story Tags: android | kotlin | location-feed-andoird | location-feed-kotlin | weekly-sponsor

TLDRvia the TL;DR App

Pusher, our weekly sponsor, makes communication and collaboration APIs that power apps all over the world, supported by easy to integrate SDKs for web, mobile, as well as most popular backend stacks. Get started.

Often times we like to track and visualize our applications in a central place. Feeds are great for this! In this tutorial, we’ll build an Android app with an activity feed that allows users to broadcast their locations and share with all other connected users in realtime.

We’ll build the Android app to monitor the activities of a Node.js REST API. Every time the endpoint of the API is hit, Pusher will publish an event with some information (location shared by the user) to a channel. This event will be received in realtime, on all the connected Android devices.

Here’s the app in action:

Prerequisites

This tutorial uses the following technologies

To follow along, you’ll need to sign up with Pusher and gain access to your dashboard to create a Pusher project. You will also need to have Android Studio v3+ installed to build the client part of this application. To build our server side script, you’ll need to download and install Node if you don’t already have it installed.

Client side

Now that you have that sorted out, let’s start building our Android app. Launch Android Studio and create a new project. Be sure to include Kotlin support. Enter an application name, in our case — Pusher-Location-Feeds

Select application’s target SDK:

Choose the basic activity template:

When the project build is completed, open your app level build.gradle file and update the dependencies like so:

Next, sync the project by clicking Sync Now with the gradle file to install the added dependencies.

Application activities

Login activity

By default creating the Android project also creates a MainActivity class and an associating activity_main.xml file for you. Now we need a login Activity to collect the users username. So create a new activity, right-click on MainActivity >> New >> Activity >> Empty Activity, then name it LoginActivity. Once this activity is created, it’ll create a default layout file activity_login.xml inside the layout folder under res. The layout will be a rather simple one, it will have a text input to collect the user’s username and a button to share their location. Here’s a snippet for the activity_login.xml file:

Here we have a simple LinearLayout with two view objects, an EditText input to collect the user’s username and a share button to send the location to the server.

Android default styling isn’t always appealing so let’s add some custom styles to our layout simply for aesthetic purposes. Under res folder, open the values folder and navigate into colors.xml file and update it with this code :

Secondly to achieve the button and Input styles, we create two drawable files. Under res right-click on drawable >>New >> Drawable resource file, name it input_bg and update it with this code:

This simply adds round edges to the EditText object. For the button styles, follow the same steps as the one above and create a new drawable file, name it button and set it up like so:

Finally update your styles.xml file inside the values folder in the layout directory:

At this point, your output in the xml visualizer should look exactly like this:

Next let’s create a new layout file called custom_view.xml. We’ll use this file to render each individual map of a user on our recyclerview object. Inside the layout folder under res, create the new layout resource file and set it up like so:

Okay, we are done with login and UI lets hook it up with it’s Java file to handle the logic. Open LoginActivity.kt file and set it up like so:

Here we are simply getting the value of the input we defined in the layout file and passing it into the MainActivity class with an intent . Once the user has entered a value (username) in the Edittext object, we set a listener on the button to call the intent action when clicked. This action will only execute if the input value is not empty.

MainActivity

Next we define a layout where we’ll render the map locations of each user when they share their location. We’ll get their latitude and longitude coordinates along with the username they provided in the LoginActivity and send it to our server, which then returns a map of the location with the provided username on the map-marker and display it on screen for all users.

Before we get into MainActivity, let’s first define a new layout file with a RecyclerView object to hold these location widgets as the users share them. Under res, right-click on layout >> New >> Layout resource file and name it content_main, (if you selected the basic activity template while setting up the project, then you should have this file by default). Open this file and set it up like so:

As seen, we simply have a RecyclerView object where we’ll render each individual user’s location so they can all appear in a list. Lastly, Open up activity_main.xml and update it:

Application logic

Since we used a RecyclerView in our layout file, we’ll need an adapter class. RecyclerView works with an Adapter to manage the items of its data source and a ViewHolder to hold a view representing a single list item. Before we create the Adapter class, lets first create a Model class that will interface between our remote data and the adapter. It’ll have the values that we’ll pass data to our recyclerview. Now right-click on MainActivity >> New >> Kotlin File/Class, name it Model, under the Kind dropdown, select Class and set it up like so:

Now that we have that, lets create the Adapter class. Right-click on MainActivity >> New >> Kotlin File/Class, name it Adapter, under the Kind dropdown, select Class again and set it up with the code:

Here we have defined an arrayList from our Model class that will be used by the adapter to populate the R``ecycler``V``iew. In the onBindViewHolder() method, we bind the locations coming from our server (as longitude and latitude) to the view holder we defined for it. We also passed the user’s username to the map marker.

Then in the onCreateViewHolder() method we define the design of the layout for individual items on the list. Finally the addItem() method adds a new instance of our model class to the arrayList and refresh the list every time we get a new addition.

Next let’s establish a connection to our Node server using the Retrofit library we installed at the beginning. First we create a new Kotlin interface to define the API endpoint we’ll be calling for this project. Right-click on MainActivity >> New >> Kotlin File/Class, under the Kind dropdown, select Interface name it Service and set it up like so:

We also need a class that’ll give us an instance of Retrofit for making networking calls. It’ll also be the class where we’ll define the server URL and network parameters. So follow the previous steps and create a class called Client.kt and set it up like this:

Replace the Base URL with your localhost address for the Node server. We’ll

The baseUrl we used here points to our local Node server running on your machine as shown above but we’ll get to that later on in the tutorial. For now let’s go back to MainActivity.kt and initialize the necessary objects and update it with the classes we’ve created above.

Here we’ve just initialized the objects we’ll need, our Adapter class, Pusher, location request and the fusedLocationClient.

In the onCreate() method we’ll setup our RecyclerView with the adapter. We’ll also call the setupPusher() method and the sendLocation() action with the floating action button:

While adding this code to your _onCreate()_ method, be careful not to miss the curly braces

So we called methods we haven’t defined yet, that’s no problem we’ll define the setupPusher() method later on in the tutorial but first off, let’s define and setup the sendLocation() method this time, outside the onCreate():

With the fusedLocationClient object we initialized earlier, we are getting the user’s location. If we succeed in getting the location, we pass the the longitude and latitude along with the user’s username into our body object. We then use it to build our HTTP request with the jsonObjects as our request parameters.

We also called the checkLocationPermission() method in the onCreate() method however we haven’t defined it yet. Lets now create this method and set it up like so:

Of course we can’t just grab every user’s location without first asking for their permission, so here’s how we set up the method that requests permission to access their location. Just after the sendLocation() method, add:x

And now let’s define the setUpPusher() method we called earlier in the onCreate() method:

Here we simply pass in our Pusher configs to the Pusher object and subscribe to the feed channel to listen for location events. Then we get the data returned from the server into our defined variables and pass them to our model class to update the adapter.

Next we implement the onStart() and onStop() methods to connect and disconnect Pusher respectively in our app:

Finally on the client side, we create a Kotlin data class that will define the payload we’ll be requesting from the server. Following the previous steps, create a class called RequestPayload and set it up like so:

Server side

Set up Pusher

Now that we have all the client side functionalities, lets go ahead and build our server. But first, if you haven’t, now will be a good time to create a free account here. When you first log in, you’ll be asked to enter some configuration options:

Enter a name, choose Android as your front-end tech, and Node.js as your back-end tech. This will give you some sample code to get you started along with your project api keys:

Then go to the App Keys tab and copy your app_id, key, and secret credentials, we’ll need them later.

Set up a Node server

For this we will use Node. So check that you have node and npm installed on your machine by running this command in command prompt:

node --version//should display version numbers

npm --version//should display version numbers

If that is not the case, Download and Install Node.

Next lets start building our server side script. Still in command prompt, run:

mkdir pusherLocationFeeds//this creates a project directory to host your project files

cd pusherLocationFeeds// this navigates into the just created directory

npm init -y//this creates a default package.json file to host our project dependencies

Let’s install the Node modules we’ll need for this project. Basically we’ll need Express, Pusher and body-parser. Inside the project directory, run:

install express, body-parser, pusher

You can always verify these installations by opening your `package.json` file, at this point the dependency block should look like this:

"dependencies": {"body-parser": "^1.18.2","express": "^4.16.3","pusher": "^1.5.1"}

Next create a server.js file in the project directory. First we require the Node modules we installed:

var express = require("express")var pusher = require("pusher")var bodyParser = require("body-parser")

Next we configure Express:

var app = express();app.use(bodyParser.json());app.use(bodyParser.urlencoded({ extended: false }));

Lets now create the Pusher object by passing the configuration object with the id, key, and the secret for the app created in the Pusher Dashboard:

var pusher = new Pusher({appId: "pusher_app_id",key: "pusher_app_key",secret: "pusher_app_secret",cluster: "pusher_app_cluster"});

As we described earlier, we’ll use Pusher to publish events that happen in our application. These events have an eventChannel, which allows them to relate to a particular topic, an eventName that is used to identify the type of the event, and a payload, which you can attach any additional information to and send back to the client.

In our case, we’ll publish an event to a Pusher channel (“feed”) when the endpoint of our API is called. Then send the information as an attachment so we can show it in an activity feed on the client side.

Here’s how we define our API’s REST endpoint:

app.post('/location', (req, res,next)=>{

    var longitude = req.body.longitude;  
    var latitude = req.body.latitude;  
    var username = req.body.username;  
  ...

Here when we receive request parameters, we’ll extract the longitude, latitude and the username of the sender from the request and send back as response to the client like so:

...pusher.trigger('feed', 'location', {longitude, latitude,username});res.json({success: 200});});

Now when a user types in a username and clicks the share location button, the server returns the data like:

{"longitude" : "longitude_value""latitude" : "latitude_value""username" : "username_value"}

From here, we then use the adapter to pass it to the ViewHolder and lay it out on the screen.When you’re done, your server.js file should look like this:

var pusher = require("pusher")var express = require("express")var Pusher = require("pusher")var bodyParser = require("body-parser")var pusher = new Pusher({appId: "app_id",key: "app_key",secret: "app_secrete",cluster: "app_cluster"});var app = express();app.use(bodyParser.json());app.use(bodyParser.urlencoded({ extended: false }));

app.post('/location', (req, res,next)=>{  
      
    var longitude = req.body.longitude;  
    var latitude = req.body.latitude;  
    var username = req.body.username;  
    
    pusher.trigger('feed', 'location', {longitude, latitude,username});  
    res.json({success: 200});  
});  
app.listen(4040, function () {  
    console.log('Listening on 4040')  
  })

Now navigate to the terminal and cd into the server.js file. Then run the server with:

node server.js

Run app

Once the server is live, go ahead and run the Android app. To run the app, keep your system connected to the internet. Back in Android Studio, click the green play icon on the menu bar to run the application or select Run from the menu and click Run ‘app’ from the dropdown. This action will launch your device modal for you to see all connected devices and emulators. If you’re using a physical device, simply select your device from the list of available devices shown and click OK.

If you’re running on an emulator, select your preferred emulator from the list of devices if you have one setup or follow these instructions to set up a new emulator:

On the devices modal, select Create New Virtual Device. This will launch a hardware selection modal where you will select any device of your choice for instance ( Nexus 5) and click Next. This will launch another modal where you will select the API level you will like to run on the device. Your can choose any of the available options for you or stick with the default and select API level 25. Click Next again to give your emulator a custom name and then click Finish to complete the setup. Now when you run the app again, you will see your emulator listed on the available devices modal. With your system still connected to the internet, select your preferred device and click Ok to run.

Conclusion

Hopefully, this tutorial has shown you in an easy way, how to build an activity feed for Android apps with Pusher. As you continue to build stuff, Perhaps you’ll see for yourself that realtime updates are of great importance. When you do, Pusher has all you’ll need to get pushing. Project is available on Github and the server side code also available on this gist.

Originally published at Pusher’s blog.

Pusher, our weekly sponsor, makes communication and collaboration APIs that power apps all over the world, supported by easy to integrate SDKs for web, mobile, as well as most popular backend stacks. Get started.


Published by HackerNoon on 2018/07/02