Firebase Realtime Database and Kotlin Tutorial – Develop Cloud Based Task List App

In this tutorial, you are going to learn about Firebase Realtime Database and Kotlin for Android. You will learn all these while developing a simple Cloud based Task List app.

What will you learn in this Tutorial

  • Connect Firebase in Android Studio?
  • Add Firebase Realtime Database support to your project?
  • Use Firebase Realtime Database for persistence in your app?
  • Use Kotlin for Android App Development?

Definitions

Here are the definitions of the some of the Terminologies and Technologies used in this Firebase Realtime Database and Kotlin Tutorial.

What is Firebase?

Firebase is Google’s mobile platform that helps you quickly develop high-quality apps and grow your business.

What is Firebase Database?

The Firebase Realtime Database is a cloud-hosted database. Data is stored as JSON and synchronized in realtime to every connected client.

What is Kotlin?

Kotlin is now an official language on Android. It’s expressive, concise, and powerful. Best of all, it’s interoperable with our existing Android languages and runtime.

Kotlin is concise while being expressive. It contains safety features for nullability and immutability, to make your Android apps healthy and performant by default.

Prerequisites

Here are the pre-requisites for the Firebase Realtime Database and Kotlin.

  1. Android Studio
  2. Firebase Console
  3. Android Mobile with Internet(Recommended but not mandatory)

Get Source Code

You can get the source file with the complete project files for the Firebase Realtime Database and Kotlin. Go ahead and click the below button to get the files.

Get Started with Firebase Realtime Database and Kotlin

To get started with the tutorial you will need to first create a Android project.

Create a Project in Android Studio

Here are the steps to create a project in Android Studio.

Create Android Project

  1. Goto File>New>New Project
  2. Set Application Name as “FirkoTasky” (FirebasekotlinTasky)
  3. Set Company domain as “appnimiacademy.com“.
  4. Set Project Location as a convenient folder on your computer.
  5. Leave the Package Name as it is.
  6. Ensure that the “Include Kotlin Support” is checked.

FirkoTasky-Create Project

NOTE: Through out this tutorial I will be using appnimiacademy in the package name. You can replace it with your own domain name.

Target Android Devices

Set Target Android Devices.

  1. Check the Phone and Tablet option.
  2. You can uncheck the “Include Android App Support” option.
  3. Uncheck other options as they are not required for this tutorial.
  4. Click on Next.

FirkoTasky-Target Android Devices

Add Activity

  1. Choose “Basic Activity” as the template for the activity.
  2. Click on Next.

FirkoTasky-Add Activity

Configure Activity

  1. Leave Activity name as default (MainActivity)
  2. Leave Layout name as default (activity_main)
  3. Leave Title as default (MainActivity)
  4. Click on Finish

FirkoTasky-Configure Activity

This is how the Android Studio should look like once the project has been created.

FirkoTasky-Android Studio Workspace-After Creating Project

Add the components to the Main Acivity

To get started we will need to add the components to the Main Activity which are required for our FirkoTasky app.

Add New Task Form in the Footer

Now let us go ahead and add a footer section at the bottom of the main activiy. It will contain the TextField and a Button to add a Task to the List.

Add a Relative Layout

Now go ahead and replace the whole TextView Tag in the “content_main.xml” with the the following code.

In the above code

  1. We are adding a RelativeLayout.
  2. There are some layout contstraints for aligments.
  3. Make sure you set the android id as shown in the code, otherwise it can lead to unexpected behaviours.
  4. Initially the New Task Form will be hidden thus the visibility is set as gone.

Add a Image Button to the Relative Layout

Now add a button to the Relative Layout. We will use this button to add a new task to the task list.

Add the following code inside the Relative Layout tag added above.

Add a Text Field for New Task

Now add the following piece of code just above the ImageButton Tag inside the RelativeLayout.

Add a ListView to show the Task List

Now you will need to add a ListView so that you can show all the exisiting Tasks in the Task List. To that paste the following code just above the Relative Layout added in the previous section.

Completed content_main.xml

The whole xml will look like as below

Row XML for Task ListView

The next component which we need to add is the rows for the Task in the list.

Create a Layout Resource File

So let us go ahead and add a resource xml.

  1. Goto to the Project Tab.
  2. Goto to the Layout Folder.
  3. Right Click on the Layout Folder.
  4. Select New.
  5. Select Resource File.
  6. Set the name as task_rows.
  7. Leave everything else as default.

FirkoTasky-Layout Folder

FirkoTasky-Task Rows XML

Change the Layout to Relative Layout

We are going to use Relative Layout for this xml. So go ahead replace the exisiting code for the layout with the following.

Add a Checkbox to Track Task Completion

We will need a checkbox to show whether a task has been completed or not.

Paste the following code inside the Relative Layout added above.

Add a TextView for Task Description

The textview will contain the description of the Task. It will be aligned to the right of the Checkbox. Paste the following code below Checkbox in the Relative Layout.

Add Button to Remove a Task

Add an image button to remove or delete a Task. Paste the following code below the TextView tag and inside the Relative Layout in the layout xml.

Completed task_rows.xml

Here is the completed xml:

This is how the Design Tab will look like for the task_rows.xml:

FirkoTasky-Task Rows Design Tab

Floating Button

We will show the footer when the user taps the Floating Button. Also we will need to change the the icon of button.

Change the Image of the Floating Button to a “+” icon

  1. Goto activity_main.xml.
  2. Find ic_dialog_email.
  3. Replace with ic_input_add.

The floating button tag will look like ths:

Add Action Handler for Floating Button

When you goto the MainActivity.kt, you will find that there is already an action handler for the fab button. It shows a snacbar at the bottom.

We are going to replace this action with a call to one of our own function.

First go ahead and add a Function to showFooter. Add the following function to MainActivity.kt

In case you get compilations errors here, add the followin imports:

Now replace the OnClickAcionListner with the following code:

Run the App

Let us run the app and see where we have reached in our Firebase Realtime Database and Kotlin tutorial.

Firebase Integeration

To get started with Firebase for the project goto menu Tools>Firebase in the Android Studio.

FirkoTasky-Tools Firebase Menu

Add Firebase

Once you click on it you will get the following wizard on the right. Expand the Firebase Relatime Database section and click on the Save and Retrive data link.

FirkoTasky-Firebase Assistant

Once you click the link it will open the Firebase Realtime Database Assistant. The Wizard will look like following.

FirkoTasky-Firebase Realtime Database Assistant

Connect to Firebase

Click on the Connect to Firebase button. Ensure that you are connected to the internet.

If you are already logged into you Firebase Console account in the Android Studio then you will get the following popup. If you are not logged in then it will ask you login to your Firebase Console.

FirkoTasky-Connect to Firebase Wizard

Click on the Connect to Firebase button. Ensure that you are connected to internet. Sometimes you might get an error like below on the bottom right.

If you get something like, just click on the Connect to Firebase once more. If things go as expected this time then you will be shown the following popup.

FirkoTasky-Existing Connection Found

Just go ahead and click on Sync button. Once everything works as expected you will get a green text Connected mentioned on the Assistant as below.

FirkoTasky-Connected to Firebase

Add Firebase Realtime Database Support

Next go ahead and click on the “Add the Realtime Database to your app” button. It will show you the following popup warning you about the changes to be made to gradle scripts.

FirkoTasky-Firebase Gradle Change Warning

You go ahead and click on “Accept Changes”. On Success you will see the following text in the Firebase Assistant tab.

FirkoTasky-Firebase Database Dependency Setup Correctly

Save New Task to Firebase Realtime Database

Let move ahead with the Tutorial now that we have the Firebase integerated into the app. In this section we will Save a new Task to the Real Time DB.

Create an Object Class for Task

We will need to have an Object class for Task in Kotlin, something similar to our good old POJO.

FirkoTasky-Add a Kotlin Class

As shown above:

  1. Goto Project Tab.
  2. Goto Package “com.appnimiacademy.firkotasky“.
  3. Right Click and Select New and then Select Kolin File/Class. A new popup will come up.
  4. Name the class as Task.
  5. Set Kind as Class.
  6. Click on OK.

FirkoTasky-Create Object Class for Task

Here is the Kotlin code for the class. Replace the code in the Task.kt file with the following.

Create a Statics.kt to hold the statics

  1. Goto Project Tab.
  2. Goto Package “com.appnimiacademy.firkotasky“.
  3. Right Click and Select New and then Select Kolin File/Class. A new popup will come up.
  4. Name the class as Statics.
  5. Set Kind as File.
  6. Click on OK.
  7. Replace the code in the file with the following code.

Get Firebase Realtime Database Reference

Add the following line of code as Class variable in MainActivity.kt. With this code you will be declaring _db as class variable for reference to the Database.

Add the following import to remove the compilation error.

Now initialise this variable by adding the following line of code to the onCreate function in MainActivity.kt

Create a function to Add Task to Database in MainActivity.kt

Add the following function to the MainActivity class.

Add a action handler to the Add Task Button

  1. Goto MainActivity.kt
  2. Goto onCreate function.
  3. Add the below code just after the floating button’s action handler.
    1. Add an action handler to the Add Task button.
    2. Call addTask() function onClick of Add Task Button.

Set the Database Rules on Firebase Console

As we are just testing we will set the rule as public. To do that just follow the below mentioned steps.

FirkoTasky-Firebase Database Rules for Testing

  1. Goto Firebase Console.
  2. Select your Project.
  3. Select Database tab.
  4. Select Realtime Database.
  5. Select Start in Test Mode.
  6. Click on Enable.

Once done it should look something like this:

FirkoTasky-Firebase Database Console

Test the Add New Task Feature

Now it is time to run the app once and validate that everthing is working fine. Here are the steps to follow to validate the app.

FirkoTasky-Add New Task Testing

  1. Run the app.
  2. Tap on the “+” floating button.
  3. Footer Form for New Task should become visible.
  4. Floating Button will hide.
  5. Fill in the New Task form in the footer.
  6. Tap on the Add buton on the right in the footer.
  7. New Task becomes visble in the Firebase Console.

FirkoTasky-Firebase New Task Added

Load Task List from Firebase Realtime Database

We have implemented the feature to add a new task. Now let us load the tasks added to the database to the listview.

Adapter Class for the Task List

The ListView needs an Adapter class to make it work.

Create the Adapter Class

Let us go ahed and create an adapter class that will be set for the list view.

  1. Goto Project Tab.
  2. Goto Package “com.appnimiacademy.firkotasky“.
  3. Right Click and Select New and then Select Kolin File/Class. A new popup will come up.
  4. Name the class as TaskAdapter.
  5. Set Kind as Class.
  6. Click on OK.
  7. Replace the code in the file with the following code.

Declare a class variable for the Adapter in the Main Activity

Initialise the class variable for the Adapeter in the Main Activity

Add the following code in he OnCreate function.

Set the Adapter for the Listview in the Main Activity

Add the following code just below the above code.

Updating the Listview

Now that the adapter for the listview is set, let us retrieve the data from Firebase Database and load it to the Listview. For that we will have to do some interim operations.

Create a Mutable List to store the task in the MainActivity

Open the MainActivity class and add the following code to declare a variable for TaskList.

Initialise the _taskList class variable

Now initialise the variable in OnCreate function.

Add a function to load the Tasks

Create a function in MainActivity to load the task.

Add a Firebase Value Event Listener

Add a class variable for the Value Event Listener to Main Actvity. Call the loadTaskList from the onDataChange function.

Now add the following code at the end in the onCreate function to set the listener.

This is how it looks when the data is loaded to the listview.

FirkoTasky-Task Rows Loaded

Checking/Unchecking of Completed Checkbox

Right now when you check or un check the checkbox for Task Completion Status, you nothing will happen. In this section we will write the code to add the functionality.

Create Task Row Listener Interface

We will need a listener which will listen to the changes to the Task Rows. For that let us first crate an interfaceclass.

  1. Goto Project Tab.
  2. Goto Package “com.appnimiacademy.firkotasky“.
  3. Right Click and Select New and then Select Kolin File/Class. A new popup will come up.
  4. Name the class as TaskRowListener.
  5. Set Kind as Interface.
  6. Click on OK.
  7. Replace the code in the file with the following code.

Implement Task Row Listener Interface

Let us implement this interaface on MainActity where we are doing all the operations. Make the change to the class declaration so that it looks like the following:

You might get compilation errors as you have not implemented the functions of the interface. To do that add the following function to the end of MainActivity.

Changes for rowListener in the Task Adapter

There needs to be ways in which the listview should be able to convey that that values have changed. To do that you will need to make changes in the Task Adapter.

Add the following class variable to the TaskAdapter.kt class:

Now set the listener for the done checkbox in the getView function of Task Adapter class.

Run the app. Now when you check or uncheck the done check box the item in the Firebase Database changes its value instantly.

FirkoTasky-Done Status Change

Deleting a Task

To delete or remove a task you are required to tap on the thrash icon of the Task row. So let us go ahead and implement the functionality.

Add onTaskDeleted function to the interface

Let us go ahead and add a function to handle task deleted in TaskRowListener Interface. Add this just below the line for onTaskChange

Implement the function in MainActivity

ClickListener for Task Remove Button in Task Adapter

Let us set the listener to handle the clicks on the delete button in the TaskAdapter class.

Run the app. Now when you tap on the delete button the item in the Firebase Database is deleted. It is highlighted with red color in the console before it is deleted.

FirkoTasky-Task Deleted

Caching

By default the caching is off for Firebase. You can switch it on by adding the following line of code. For this app you can add it in the OnCreate function. For multiple acticity apps you will need to add it to the Application class.

Conclusion

So we come to the end of this tutorial. I hope you liked it more than I loved it researching and writing it.

Firebase is an awesome tool which can help you get started with internet based apps withou any knowledge of server side programming.

Using it wisely can help you launch your apps to the world in no time.

 

Posted in Tutorials and tagged , , , .

Neeraj Jaiswal has been programming from 1989. He has been developing apps from 2004 and has never looked back. He has developed apps for almost all the mobile and desktop platforms available in the market. With multi-million downloads some of the app have been the among the best sellers. He has also been sharing his app development knowledge and has more than 35,000 students across 154 countries of the world. He is also the the founder and CEO of Appnimi, an app development company started in 2010

4 Comments

  1. Thanks for this turoial.
    But there is a bug :
    When there is only one task on the screen and you try to delete it by clicking on the the trash icon or directely from firebase, the task is remaining on the screen.
    I don’t understand from where comes this bug.

    Could you take a look and explain ?

    Thanks,
    Alex.

  2. Loearned allot form your tutorial, big help
    However in the list Adapter I get an error I cant figure out from this line
    class TaskAdapter(context: Context, taskList: MutableList) : BaseAdapter() {

    Error one type argument expected for interface mutablelist
    What shouold I put in there, please

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.