Latest news about Bitcoin and all cryptocurrencies. Your daily crypto news habit.
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 numbersnpm --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 filescd pusherLocationFeeds// this navigates into the just created directorynpm 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.
Build a location feed app for Android with Kotlin was originally published in Hacker Noon on Medium, where people are continuing the conversation by highlighting and responding to this story.
Disclaimer
The views and opinions expressed in this article are solely those of the authors and do not reflect the views of Bitcoin Insider. Every investment and trading move involves risk - this is especially true for cryptocurrencies given their volatility. We strongly advise our readers to conduct their own research when making a decision.