Back to search

Implement push notifications in Kotlin to create a food delivery app

  • Graham Cox
July 12th, 2018
You will need some experience of Kotlin, and familiarity with Android Studio. You will also need Node and Create React App installed.

Introduction

Many business need to be very responsive to customer requests in order to be competitive. This works both ways - the business being informed immediately when a new order comes in, and the customer being informed as to the progress of their order.

In this article we are going to build a simple takeaway application, featuring a web app for the takeaway itself to use, and an Android app for customers. The web app will be updated automatically using Pusher Channels, and the Android app will receive notifications using Pusher Beams so that the customer and staff are always aware of everything going on.

kotlin-takeaway-demo

Prerequisites

In order to follow along, you will need some experience with the Kotlin programming language, which we are going to use for both the backend and frontend of our application, as well as with Android development.

We are going to be building the web UI that the takeaway uses with Create React App, so ensure that this is installed, along with a recent version of Node.js.

You will also need appropriate IDEs. We suggest IntelliJ IDEA and Android Studio. Finally, you will need a free Pusher Account. Sign up now if you haven’t already done so.

Overall design

Our overall application will have a backend application, a web UI that is to be used by the takeaway company, and an Android application that is targeted to the customers. Customers will order food using the Android application, and the orders will appear in the web UI in real time using Pusher Channels. The takeaway company can then use the web UI to update progress on the orders, which will be sent directly to the customer’s device using Pusher Beams, keeping them updated on the progress of their order. The backend application then acts as orchestration between the two UIs.

Setting up your Pusher accounts

We are going to use two different Pusher accounts for this application - a Pusher Channels account for real time updates of the web UI, and a Pusher Beams account for notifying the customers of the status of their orders.

Registering for Pusher Channels

In order to follow along, you will need to create a free Pusher account. This is done by visiting the Pusher dashboard and logging in, creating a new account if needed. Next click on Channels apps on the sidebar, followed by Create Channels app.

kotlin-takeaway-channels

Fill out this dialog as needed and then click the Create my app button. Then click on App Keys and note down the credentials for later.

kotlin-takeaway-keys

Registering for Pusher Beams

In order to use the Beams API and SDKs from Pusher, you also need to create a new Beams instance in the Pusher Beta Dashboard.

Next, on your Overview for your Beams instance, click Open Quickstart to add your Firebase Cloud Messaging (FCM) Server Key to the Beams Instance.

After saving your FCM key, you can finish the Quickstart wizard by yourself to send your first push notification, or just continue as we’ll cover this below.

It’s important to make sure that you download and keep the google-services.json file from the Firebase Console as we are going to need this later on.

Once you have created your Beams instance, you will also need to note down your Instance Id and Secret Key from the Pusher Dashboard, found under the CREDENTIALS section of your Instance settings.

Backend application

We are going to build our backend application using Spring Boot and the Kotlin programming language, since this gives us a very simple way to get going whilst still working in the same language as the Android app.

Head over to https://start.spring.io/ to create our project structure. We need to specify that we are building a Gradle project with Kotlin and Spring Boot 2.0.2 (or newer if available at the time of reading), and we need to include the “Web” component:

kotlin-takeaway-spring-initializer

The Generate Project button will give you a zip file containing our application structure. Unpack this somewhere. At any time, you can execute ./gradlew bootRun to build and start your backend server running.

Firstly though, we need to add some dependencies. Open up the build.gradle file and add the following to the dependencies section:

    compile 'com.pusher:pusher-http-java:1.0.0'
    compile 'com.pusher:push-notifications-server-java:0.9.0'
    runtime 'com.fasterxml.jackson.module:jackson-module-kotlin:2.9.2'

The first of these is the Pusher library needed for triggering push notifications. The second is the Jackson module needed for serializing and deserializing Kotlin classes into JSON.

Now, build the project. This will ensure that all of the dependencies are downloaded and made available and that everything compiles and builds correctly:

    $ ./gradlew build
    Starting a Gradle Daemon (subsequent builds will be faster)

    > Task :test
    2018-04-27 07:34:27.548  INFO 43169 --- [       Thread-5] o.s.w.c.s.GenericWebApplicationContext   : Closing org.springframework.web.context.support.GenericWebApplicationContext@c1cf60f: startup date [Fri Apr 27 07:34:25 BST 2018]; root of context hierarchy


    BUILD SUCCESSFUL in 17s
    5 actionable tasks: 5 executed

Required endpoints

Our backend application will have endpoints for the customer and staff UI to work with. The customer endpoints are:

  • GET /menu-items
  • POST /orders

Whilst the staff endpoints are:

  • GET /orders
  • PUT /orders/{id}/status
  • PUT /orders/{id}/items/{id}/status

An orders resource will contain a number of menu-items entries, with the status of them. The customer application will create a new order containing a simple list of these entries, and then the staff application will update the status of each item as is completed. Once they are all completed it will then update the order status to indicate that the food is out for delivery, and that it has been delivered.

The creation of an order will cause a Pusher Channels message to be sent out, containing the new order. Every time an order is updated will cause a Pusher Beams message to be sent out, containing the status of that order.

Listing menu items

The first thing we’ll do is to support listing of menu items.

Firstly we want to actually represent our menu items. In this case we’ll go for something very simple - just an name and an ID - but in reality you could include whatever details are needed. Create a new class called MenuItem as follows:

    data class MenuItem(
            val id: String,
            val name: String
    )

Then we’ll create a class to represent our DAO layer for loading menu items. This will be entirely hard-coded in this application, but in reality would work in terms of a database. Create a new class called MenuItemDao as follows:

    @Component
    class MenuItemDao {
        private val menuItems = listOf(
                MenuItem(id = "cheese_tomato_pizza", name = "Cheese & Tomato Pizza"),
                MenuItem(id = "hot_spicy_pizza", name = "Hot & Spicy Pizza"),
                MenuItem(id = "vegetarian_pizza", name = "Vegetarian Supreme Pizza"),
                MenuItem(id = "garlic_bread", name = "Garlic Pizza Bread"),
                MenuItem(id = "donner_kebab", name = "Donner Kebab"),
                MenuItem(id = "chicken_tikka_kebab", name = "Chicken Tikka Kebab"),
                MenuItem(id = "chicken_strips", name = "Chicken Strips (7)"),
                MenuItem(id = "beef_burger", name = "Beef Burger"),
                MenuItem(id = "cheeseburger", name = "Cheeseburger")
        )

        fun listMenuItems() = menuItems
    }

Note: the @Component annotation means that Spring will automatically find this class and make it available for other classes to use.

Now we’ll create a controller to list these menu items. Create a new class called MenuItemController as follows:

    @RestController
    @CrossOrigin
    class MenuItemController(private val dao: MenuItemDao) {
        @RequestMapping("/menu-items")
        fun getMenuItems() = dao.listMenuItems()
    }

Note: the @CrossOrigin annotation makes this controller accessible from web applications running on a different host and/or port.

Managing orders

The next part is to manage the orders themselves. For this we want to be able to create, update and list the orders that are being processed.

Firstly we will create a representation of the order itself. For this, create a class called Order as follows:

    enum class OrderItemStatus {
        PENDING,
        STARTED,
        FINISHED
    }

    enum class OrderStatus {
        PENDING,
        STARTED,
        COOKED,
        OUT_FOR_DELIVERY,
        DELIVERED
    }

    data class OrderItem(
            val id: String,
            val menuItem: String,
            var status: OrderItemStatus
    )

    data class Order(
            val id: String,
            var status: OrderStatus,
            val items: List<OrderItem>
    )

You’ll note that there are actually 4 classes here. These represent, between them, the entire order. A single order contains a status and a list of order items, where a single order item contains a menu item and the status of that order item. This allows us to update each order item independently of any others, including if one order contains multiples of the same menu item.

Next, create a new class called OrderDao. This is going to represent our data storage for orders and order items.

    @Component
    class OrderDao {
        private val orders = mutableListOf<Order>()

        fun createNewOrder(items: List<String>) : Order {
            val orderId = UUID.randomUUID().toString()
            val orderItems = items.map { menuItem ->
                val orderItemId = UUID.randomUUID().toString()
                OrderItem(id = orderItemId, menuItem = menuItem, status = OrderItemStatus.PENDING)
            }

            val order = Order(id = orderId, items = orderItems, status = OrderStatus.PENDING)
            orders.add(order)

            return order
        }

        fun removeOrder(orderId: String) {
            orders.removeIf { order -> order.id == orderId }
        }

        fun listOrders(): List<Order> = orders

        fun getOrderById(id: String) = orders.first { order -> order.id == id }
    }

Finally, we want a controller that can be used to interact with orders. For this, create a new class called OrderController as follows:

    @RestController
    @RequestMapping("/orders")
    @CrossOrigin
    class OrderController(private val orderDao: OrderDao) {
        @RequestMapping(method = [RequestMethod.GET])
        fun listOrders() = orderDao.listOrders()

        @RequestMapping(method = [RequestMethod.POST])
        fun createOrder(@RequestBody items: List<String>): Order {
            val order = orderDao.createNewOrder(items)

            // notifier call to go here
            return order
        }

        @RequestMapping(value = ["/{order}/status"], method = [RequestMethod.PUT])
        fun updateOrderStatus(@PathVariable("order") orderId: String,
                              @RequestBody newStatus: OrderStatus): Order {
            val order = orderDao.getOrderById(orderId)
            order.status = newStatus

            if (order.status == OrderStatus.DELIVERED) {
                orderDao.removeOrder(orderId)
            }

            // notifier call to go here
            return order
        }

        @RequestMapping(value = ["/{order}/items/{item}/status"], method = [RequestMethod.PUT])
        fun updateOrderItemStatus(@PathVariable("order") orderId: String,
                                  @PathVariable("item") itemId: String,
                                  @RequestBody newStatus: OrderItemStatus): Order {
            val order = orderDao.getOrderById(orderId)
            order.items.first { item -> item.id == itemId }
                    .status = newStatus

            if (order.items.all { item -> item.status == OrderItemStatus.FINISHED }) {
                order.status = OrderStatus.COOKED
            } else if (order.items.any { item -> item.status != OrderItemStatus.PENDING }) {
                order.status = OrderStatus.STARTED
            }

            // notifier call to go here
            return order
        }
    }

This has some business logic around when the status of an order or an order item is updated, in order to correctly transition the order through it’s lifecycle.

Note: there is no error handling here. Actions such as providing an invalid ID or status will cause a bad error to be returned. In a real application this would need to be handled properly, but for this article we don’t need to worry about it.

Sending update notifications

Once we have our backend server able to manage our orders and order items, we need to keep all of our clients updated. This includes both the web UI for the restaurant and the Android UI for the customers. For this, we are going to be sending events using both Pusher Beams and Pusher Channels.

For this, we will first create a new class called OrderNotifier as follows:

    @Component
    class OrderNotifier(
            @Value("\${pusher.beams.instance_id}") beamsInstanceId: String,
            @Value("\${pusher.beams.secret}") beamsSecretKey: String,
            @Value("\${pusher.channels.app_id}") channelsAppId: String,
            @Value("\${pusher.channels.key}") channelsKey: String,
            @Value("\${pusher.channels.secret}") channelsSecret: String,
            @Value("\${pusher.channels.cluster}") channelsCluster: String
    ) {

        private val beams: PushNotifications = PushNotifications(beamsInstanceId, beamsSecretKey)
        private val channels: Pusher = Pusher(channelsAppId, channelsKey, channelsSecret)

        init {
            channels.setCluster(channelsCluster)
            channels.setEncrypted(true)
        }

        fun notify(order: Order) {
            sendBeamsNotification(order)
            sendChannelsNotification(order)
        }

        private fun sendBeamsNotification(order: Order) {
            val itemStatusCounts = order.items.groupBy { it.status }
                    .mapValues { it.value.size }

            beams.publish(listOf(order.id),
                    mapOf(
                            "fcm" to mapOf(
                                    "data" to mapOf(
                                            "order" to order.id,
                                            "status" to order.status.name,
                                            "itemsPending" to (itemStatusCounts[OrderItemStatus.PENDING] ?: 0).toString(),
                                            "itemsStarted" to (itemStatusCounts[OrderItemStatus.STARTED] ?: 0).toString(),
                                            "itemsFinished" to (itemStatusCounts[OrderItemStatus.FINISHED] ?: 0).toString()
                                    )
                            )
                    ))
        }

        private fun sendChannelsNotification(order: Order) {
            channels.trigger("orders", "order-update", mapOf(
                    "order" to order.id,
                    "status" to order.status.name
            ))
        }
    }

Then we will wire this up in our controller. Update the constructor definition of OrderController as follows:

    class OrderController(private val orderDao: OrderDao, private val orderNotifier: OrderNotifier) {

Then add the following to each of the createOrder, updateOrderStatus and updateOrderItemStatus methods, immediately before the return:

    orderNotifier.notify(order)

Finally, we need to actually configure our system. This is done in application.properties, as follows:

    pusher.channels.app_id=CHANNELS_APP_ID
    pusher.channels.key=CHANNELS_KEY
    pusher.channels.secret=CHANNELS_SECRET
    pusher.channels.cluster=CHANNELS_CLUSTER

    pusher.beams.instance_id=BEAMS_INSTANCE_ID
    pusher.beams.secret=BEAMS_SECRET

Note: remember to replace CHANNELS_APP_ID, CHANNELS_KEY, CHANNELS_SECRET, CHANNELS_CLUSTER, BEAMS_INSTANCE_ID and BEAMS_SECRET with the appropriate values obtained when you registered your Pusher application details.

At this point, our backend does everything necessary to support this application.

Takeaway web application

The next part is to build the web application that the takeaway will use to fulfil orders. We’re going to use Create React App for that. Firstly, we’ll create the webapp structure itself:

    $ create-react-app takeaway-webapp
    $ cd takeaway-webapp
    $ npm install --save axios pusher-js semantic-ui-react semantic-ui-css

This also installs the modules for communicating with our backend - axios for making HTTP calls and pusher-js for receiving the Pusher Channels messages - as well as Semantic UI for our styling.

Note: at the time of writing, this also installs babel/runtime version 7.0.0-beta.48, which has a serious bug in it. If this is still the case then you can fix this by running npm install --`save @babel/runtime@7.0.0-beta.47`.

Firstly we’ll create a component for rendering a single order. This is fully self-contained in this example, but in reality you might choose to separate out into smaller components. Create a new file called src/Order.js as follows:

    import React from 'react';
    import { Segment, Table, Button } from 'semantic-ui-react'
    import axios from 'axios';
    function updateOrderItem(order, item, newStatus) {
        axios.put(`http://localhost:8080/orders/${order.id}/items/${item.id}/status`,
            newStatus,
            {
                transformRequest: (data) => `"${data}"`,
                headers: {
                    'Content-Type': 'application/json'
                }
            });
    }
    function updateOrder(order, newStatus) {
        axios.put(`http://localhost:8080/orders/${order.id}/status`,
            newStatus,
            {
                transformRequest: (data) => `"${data}"`,
                headers: {
                    'Content-Type': 'application/json'
                }
            });
    }
    function OrderItemButton({ order, item }) {
        if (item.status === 'PENDING') {
            return <Button onClick={() => updateOrderItem(order, item, 'STARTED')}>Start Work</Button>;
        } else if (item.status === 'STARTED') {
            return <Button onClick={() => updateOrderItem(order, item, 'FINISHED')}>Finish Work</Button>;
        } else {
            return <div>Finished</div>;
        }
    }
    function OrderButton({ order }) {
        if (order.status === 'COOKED') {
            return <Button onClick={() => updateOrder(order, 'OUT_FOR_DELIVERY')}>Out for Delivery</Button>;
        } else if (order.status === 'OUT_FOR_DELIVERY') {
            return <Button onClick={() => updateOrder(order, 'DELIVERED')}>Delivered</Button>;
        } else {
            return null;
        }
    }
    export default function Order({ order }) {
        const items = order.items.map((item) => (
            <Table.Row key={item.id}>
                <Table.Cell>
                    {item.name}
                </Table.Cell>
                <Table.Cell>
                    <OrderItemButton order={order} item={item} />
                </Table.Cell>
            </Table.Row>
        ));
        return (
            <Segment vertical>
                <Table striped>
                    <Table.Body>
                        {items}
                    </Table.Body>
                </Table>
                <OrderButton order={order} />
            </Segment>
        );
    }

Note: this makes calls to http://localhost:8080. In reality you will need to replace this with the real URL to your backend service.

This will render a table containing all of the order items, each of which has a button next to it to update the status of that item. There will also be a button, if applicable, below the table to update the delivery status of the entire order.

Next we’ll create a simple component to render the complete list of orders. Create src/OrdersList.js as follows:

    import React from 'react';
    import Order from './Order';
    export default ({ orders }) => {
        const orderElements = orders.map((order) => <Order order={order} key={order.id} />);
        return (
            <div>
                {orderElements}
            </div>
        );
    };

Now we need to actually connect this to our APIs. For this we will create a file called src/ConnectedOrdersList.js - so called because it’s not a UI component but a connecting component that makes API calls instead - as follows:

    import React from 'react';
    import axios from 'axios';
    import Pusher from 'pusher-js';
    import OrdersList from './OrdersList';
    const socket = new Pusher('<CHANNELS__KEY>', {
        cluster: '<CHANNELS_CLUSTER>',
    });
    export default class ConnectedOrdersList extends React.Component {
        state = {
            orders: []
        };
        render() {
            return (
                <div className="ui container">
                    <OrdersList orders={this.state.orders} />
                </div>
            );
        }
        componentDidMount() {
            this._fetchOrders();
            socket.subscribe('orders')
                .bind('order-update', () => this._fetchOrders());
        }
        _fetchOrders() {
            const ordersPromise = axios.get('http://localhost:8080/orders')
            const menuItemsPromise = axios.get('http://localhost:8080/menu-items');
            Promise.all([ordersPromise, menuItemsPromise])
                .then((values) => {
                    const menuItems = {};
                    values[1].data.forEach((entry) => {
                        menuItems[entry.id] = entry.name;
                    });
                    const orders = values[0].data.map((order) => {
                        return {
                            id: order.id,
                            status: order.status,
                            items: order.items.map((item) => {
                                return {
                                    id: item.id,
                                    menuItem: item.menuItem,
                                    status: item.status,
                                    name: menuItems[item.menuItem]
                                };
                            })
                        };
                    });
                    this.setState({
                        orders: orders
                    });
                });
        }
    }

Note: ensure you replace <CHANNELS_KEY> and <CHANNELS_CLUSTER> with the same values as used in the backend application.

This contains a method that will make two API calls - one each to our /menu-items and /orders endpoints - and combine the results together. Then it will update the component state with this result, which will cause it to render our Orders component with the resultant list. We also register to listen to the Pusher events that we broadcast earlier so that every time we get an indication that the orders have changed we can go and refresh our list.

Finally, replace the contents of src/App.js with the following:

    import React, { Component } from 'react';
    import 'semantic-ui-css/semantic.min.css';
    import OrdersList from './ConnectedOrdersList';
    class App extends Component {
      render() {
        return (
          <div className="App">
            <OrdersList />
          </div>
        );
      }
    }
    export default App;

This renders our ConnectedOrdersList component that we’ve just defined as the main body of our application.

At this point, we have a fully functional web UI that the takeaway can use to manage the orders:

kotlin-takeaway-stage-1

Building the customers application

The customers Android application will also be built in Kotlin, using Android Studio. To start, open up Android Studio and create a new project, entering some appropriate details and ensuring that you select the Include Kotlin support option. Note that the Package name must match that specified when you set up the FCM Server Key earlier.

kotlin-takeaway-create-android

Then on the next screen, ensure that you select support for Phone and Tablet using at least API 23:

kotlin-takeaway-target-devices

Ensure that an Google Maps Activity is selected:

kotlin-ridesharing-create-android-7

And set the Activity Name to “MainActivity” and Layout Name to “activity_main”:

kotlin-takeaway-main

Next we need to add some dependencies to our project to support Pusher. Add the following to the project level build.gradle, in the existing dependencies section:

    classpath 'com.google.gms:google-services:3.2.1'

Then add the following to the dependencies section of the app level build.gradle:

    implementation 'com.google.firebase:firebase-messaging:15.0.0'
    implementation 'com.pusher:push-notifications-android:0.10.0'

    compile 'com.loopj.android:android-async-http:1.4.9'
    compile 'com.google.code.gson:gson:2.2.4'

And this to bottom of the app level build.gradle:

    apply plugin: 'com.google.gms.google-services'

Next, copy the google-services.json file we downloaded earlier into the app directory under your project. We are now ready to actually develop our specific application using these dependencies.

Finally, we need to add some permissions to our application. Open up the AndroidManifest.xml file and add the following immediately before the <application> tag:

    <uses-permission android:name="android.permission.INTERNET"/>

Displaying the menu items

The main screen that we are going to show is a list of menu items, allowing the user to place an order.

Firstly, we need our main application layout. For this, update app/res/layout/activity_main.xml as follows:

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#fff">

        <ScrollView
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical">

                <ListView
                    android:id="@+id/records_view"
                    android:layout_width="match_parent"
                    android:layout_height="500dp"
                    android:layout_marginTop="16dp">

                </ListView>
            </LinearLayout>
        </ScrollView>

        <Button
            android:id="@+id/button2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Place Order" />

    </LinearLayout>

Note: in order to paste this snippet in, the Text tab at the bottom of the screen should be selected.

Note: sometimes, copy and paste of the entire file into the Text tab will cause a blank line at the very top. This is invalid XML and needs to be removed.

This gives us a list to show our menu items, and a button with which to place the order.

Now we need a class to represent each entry in this list. Create a new class called MenuItem as follows:

    data class MenuItem(
            val id: String,
            val name: String
    )

You’ll notice that this is identical to the MenuItem class on the backend. This is unsurprising since it represents the exact same data.

Next we need a layout to represent a single row in our list. For this, create a new layout resource called app/res/layout/menuitem.xml as follows:

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="horizontal" android:layout_width="match_parent"
        android:layout_height="match_parent">
        <TextView
            android:id="@+id/item_name"
            android:textColor="#000"
            android:fontFamily="serif"
            android:layout_height="wrap_content"
            android:layout_width="match_parent"
            android:layout_weight="1"
            android:text="Name"/>
        <Spinner
            android:id="@+id/item_count"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="3" />
    </LinearLayout>

This has two entries in it - an item name and a spinner. The spinner control is effectively a dropdown, and will be used to select how many of each item to order.

Now we need to be able to render this new layout for each of our menu items. For this, create a new class called MenuItemAdapter as follows:

    class MenuItemAdapter(private val recordContext: Context) : BaseAdapter() {
        var records: List<MenuItem> = listOf()
            set(value) {
                field = value
                notifyDataSetChanged()
            }

        override fun getView(i: Int, view: View?, viewGroup: ViewGroup): View {
            val theView = if (view == null) {
                val recordInflator = recordContext.getSystemService(Activity.LAYOUT_INFLATER_SERVICE) as LayoutInflater

                val theView = recordInflator.inflate(R.layout.menuitem, null)
                val newMenuItemViewHolder = MenuItemViewHolder(
                        theView.findViewById(R.id.item_name),
                        theView.findViewById(R.id.item_count)
                )
                val countAdapter = ArrayAdapter(
                        recordContext,
                        android.R.layout.simple_spinner_dropdown_item,
                        IntRange(0, 10).toList().toTypedArray()
                )
                newMenuItemViewHolder.count.adapter = countAdapter
                theView.tag = newMenuItemViewHolder

                theView
            } else {
                view
            }

            val menuItemViewHolder = theView.tag as MenuItemViewHolder

            val menuItem = getItem(i)
            menuItemViewHolder.name.text = menuItem.name
            menuItemViewHolder.id = menuItem.id

            return theView
        }

        override fun getItem(i: Int) = records[i]

        override fun getItemId(i: Int) = 1L

        override fun getCount() = records.size
    }

    data class MenuItemViewHolder(
            val name: TextView,
            val count: Spinner
    ) {
        var id: String? = null
    }

Amongst other things, this includes a hard-coded list of values for the spinner control - allowing the user to order up to 10 of any single item.

Finally we just need to get the data into this list. Update MainActivity by adding the following field to the class:

    private lateinit var recordAdapter: MenuItemAdapter

Then initialize this by adding the following to our MainActivity class:

    override fun onResume() {
        super.onResume()
        recordAdapter = MenuItemAdapter(this)
        val recordsView = findViewById<View>(R.id.records_view) as ListView
        recordsView.setAdapter(recordAdapter)

        refreshMenuItems()
    }

Next we just need to implement the refreshMenuItems method, as follows:

    private fun refreshMenuItems() {
        val client = AsyncHttpClient()
        client.get("http://10.0.2.2:8080/menu-items", object : JsonHttpResponseHandler() {
            override fun onSuccess(statusCode: Int, headers: Array<out Header>, response: JSONArray) {
                super.onSuccess(statusCode, headers, response)
                runOnUiThread {
                    val menuItems = IntRange(0, response.length() - 1)
                            .map { index -> response.getJSONObject(index) }
                            .map { obj ->
                                MenuItem(
                                        id = obj.getString("id"),
                                        name = obj.getString("name")
                                )
                            }

                    recordAdapter.records = menuItems
                }
            }
        })
    }

Note: The import for Header should be cz.msebera.android.httpclient.Header

Note: 10.0.2.2 is the IP Address that the host machine appears when running inside the Android emulator. In reality you will want to use the real host of your service.

At this point we can start up the Android application and see all of the menu choices:

kotlin-takeaway-stage-2

Placing an order

Now that we can see the list of items that can be ordered, we need to be able to place an order.

Firstly, we need to be able to get the list of items that have been selected to be ordered. This will be coming out of the MenuItemAdapter class, as this acts as the interface to the list of items.

Firstly, create a couple of fields in this class as follows:

    private val currentOrder = mutableMapOf<String, Int>()

    val order: List<String>
        get() = currentOrder.filterValues { it > 0 }
                .map { orderItem -> List(orderItem.value) { orderItem.key } }
                .flatten()

The first of these is a private map that will act as a mapping between each item and the number of that item to order. The second is a computed property that returns a list of the items to order, with one entry for each item. This means that if we order three pizzas, there will be three entries in this list.

Next, add a handler towards the bottom of the getView method, immediately before the return statement, to update our map of orders:

    menuItemViewHolder.count.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
        override fun onNothingSelected(parent: AdapterView<*>?) {
            currentOrder.remove(menuItem.id)
        }

        override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
            currentOrder[menuItem.id] = position
        }
    }

This is triggered every time a new value is selected for any item, and will cause our map to be updated to match.

Now we can use this to actually make the HTTP call to place our order. For this we need to create a new method called placeOrder in the MainActivity class, as follows:

    fun placeOrder(view: View) {
        val items = recordAdapter.order
        if (items.isEmpty()) {
            Toast.makeText(this, "No items selected", Toast.LENGTH_LONG)
                    .show()
        } else {

            val request = JSONArray(items)

            val client = AsyncHttpClient()
            client.post(applicationContext, "http://10.0.2.2:8080/orders", StringEntity(request.toString()),
                    "application/json", object : JsonHttpResponseHandler() {

                override fun onSuccess(statusCode: Int, headers: Array<out Header>, response: JSONObject) {
                    runOnUiThread {
                        Toast.makeText(this@MainActivity, "Order placed", Toast.LENGTH_LONG)
                                .show()
                    }
                }
            })
        }
    }

Note: the “this@MainActivity” syntax means to get the “this” value that refers to the “MainActivity” class, as opposed to the “JsonHttpResponseHandler” inner class that we’re actually executing inside.

Then we can update our activity_main.xml file so that the Button element reads as follows:

    <Button
        android:id="@+id/button2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Place Order"
        android:onClick="placeOrder" />

This now does everything necessary to place an order on the server, including displaying an error message if the user did not select any items to order when pressing the button.

Receiving order update notifications

Now that we can place orders, we want to be notified as to the progress of the order. This will include a progress bar for the part of the process where the order is being prepared, and then simple strings to indicate that the order is out for delivery.

The first thing we need to do is enable support for receiving push notifications for our events. Add the following to the end of the onCreate method of MainActivity:

    PushNotifications.start(getApplicationContext(), "BEAMS_INSTANCE_ID")

Note: remember to replace BEAMS_INSTANCE_ID with the appropriate value obtained when you registered your Pusher Beams application details.

Next we want to register to receive notifications for our order. This is done by adding the following in to the onSuccess callback method inside the placeOrder method:

    val id = response.getString("id")
    PushNotifications.subscribe(id)

At this point, every time the order changes, the Android app will receive a push notification informing of the changes. We can now display android notifications to inform the user of the current status. Create a new method called receiveNotification in the MainActivity class as follows:

    private fun receiveNotifications() {

        val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channel = NotificationChannel("takeaway",
                    "Pusher Takeaway",
                    NotificationManager.IMPORTANCE_DEFAULT)
            notificationManager.createNotificationChannel(channel)
        }

        PushNotifications.setOnMessageReceivedListenerForVisibleActivity(this, object : PushNotificationReceivedListener {
            override fun onMessageReceived(remoteMessage: RemoteMessage) {
                Log.i("Notification", remoteMessage.data.toString())

                val pending = remoteMessage.data["itemsPending"]?.toInt() ?: 0
                val started = remoteMessage.data["itemsStarted"]?.toInt() ?: 0
                val finished = remoteMessage.data["itemsFinished"]?.toInt() ?: 0

                val total = pending + started + finished

                val notification = when(remoteMessage.data["status"]) {
                    "STARTED" -> {
                        NotificationCompat.Builder(applicationContext, "takeaway")
                                .setSmallIcon(R.mipmap.ic_launcher)
                                .setContentTitle("Your order")
                                .setContentText("Your order is being cooked")
                                .setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
                                .setPriority(NotificationCompat.PRIORITY_DEFAULT)
                                .setProgress(total, finished, finished == 0)
                    }
                    "COOKED" -> {
                        NotificationCompat.Builder(applicationContext, "takeaway")
                                .setSmallIcon(R.mipmap.ic_launcher)
                                .setContentTitle("Your order")
                                .setContentText("Your order is ready")
                                .setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
                                .setPriority(NotificationCompat.PRIORITY_DEFAULT)
                                .setProgress(total, total, false)
                    }
                    "OUT_FOR_DELIVERY" -> {
                        NotificationCompat.Builder(applicationContext, "takeaway")
                                .setSmallIcon(R.mipmap.ic_launcher)
                                .setContentTitle("Your order")
                                .setContentText("Your order is out for delivery")
                                .setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
                                .setPriority(NotificationCompat.PRIORITY_DEFAULT)
                    }
                    "DELIVERED" -> {
                        NotificationCompat.Builder(applicationContext, "takeaway")
                                .setSmallIcon(R.mipmap.ic_launcher)
                                .setContentTitle("Your order")
                                .setContentText("Your order is outside")
                                .setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
                                .setPriority(NotificationCompat.PRIORITY_DEFAULT)
                    }
                    else -> null
                }

                notification?.let {
                    notificationManager.notify(0, it.build())
                }
            }
        })
    }

Note: if it is ambiguous, the NotificationCompat import should be for android.support.v4.app.NotificationCompat.

And then call this new method from the onResume method:

    receiveNotifications()

This gives everything for the customer to keep updated with their order. Ensure that the backend and web UI are running, and then we can test it all out together.

kotlin-takeaway-demo

Conclusion

This article has hopefully shown how easy it can be to integrate Pusher technologies into your application to give real time updates to both the customer and staff user interfaces. Even though we use two totally different Pusher technologies - Pusher Channels and Pusher Beams - they work seamlessly together to give a full featured experience.

The full source code for this article is available on GitHub. Why not try extending it support more functionality - for example, multiple restaurants.

  • Beams
  • Channels

© 2018 Pusher Ltd. All rights reserved.

Pusher Limited is a company registered in England and Wales (No. 07489873) whose registered office is at 28 Scrutton Street, London EC2A 4RP.