Firestore with Kotlin

Firestore as a backend dynamic database for a Kotlin Android Application

Introduction

Hi there, If you are looking to work with the Cloud Firestore using Kotlin, you are at the right place. Cloud Firestore (currently in beta release) is a realtime database which is a flexible and scalable database for a mobile, web, server and cloud applications. Most of the modern applications are switching to a realtime database for an Expressive querying, a quick realtime data updates, offline/online data sync and scalability. Cloud Firestore is one of most reliable, secure and flexible for complex data structures.Protect access to your data in Cloud Firestore with Firebase Authentication and Cloud Firestore Security Rules for Android, iOS, and JavaScript, or Identity and Access Management (IAM) for server-side languages. Check this video to get introduced to Firestore.

Working with data

Cloud Firestore is nothing but a cloud hosted database NoSQL data model which saves data in documents contains fields mapping to values. Documents are organised in Collections. Cloud Firestore is optimized for storing large collections of small documents. Documents can contain sub collections and nested objects, both of which can include primitive fields like strings or complex objects like lists.

Cloud Firestore Documents data supports following data types:

  • Array – Sort by elements if not same else by length
  • Boolean – false or true
  • Bytes . Only first 1500 bytes are considered by the queries
  • Date Time – Chronological
  • Float – numeric – floating point number
  • Geographical point – by latitude then longitude
  • Int – numeric – Integer number
  • Map – key value – example {“foo”: “bar”}
  • null – None
  • Reference – path elements – project/[ID]/some/thing/doc/here
  • Text String – UTF-8 encoded byte

Setting up Firestore

Before going to the set up your database in Firestore. You should set up your Firebase account and register a new App in your Firebase Console. To set up a firebase account all you need is a Gmail account. Go to the FIREBASE CONSOLE and create a new project if no project exists or click on the existing project to the Firebase dashboard. In Firebase Dashboard, you can find the ‘Database’ option on the left side navigation menu (Develop > Database). Click on it and you can see a Cloud Firestore database introduction screen and hit the ‘Create Database’ button. You are asked to choose the security rules, go with the ‘Locked Mode’. After settings the rules, you are directed to the Database dashboard. Hurray! You did it. Please follow the steps described below to create a Firestore database or the Slider.

Double on this slider for full screen view

Step 1 - Go to the Firebase Console
null

Step 2 - Create a project
null

Step 3 - Project successfully created
null

Step 4 - Welcome to the Firebase Dashbaord

Step 5 - Click 'Database' option on the left side menu.
null

Step 6 - Click on 'Create Database' on Cloud Firestore section and you will see the screen as below

As if now, let's 'Start' with locked mode - security rule

Step 7 - Setting up the security rules

Step 8 - Successfully database created with your project name

Setting Up SDK in your project

From the above steps you have successfully created a Firestore database in your Firebase console. Now, let us see the further steps to set the Firebase SDK in your App. Click on the the ‘Settings‘ icon on the top left section – besides the ‘Project Overview‘ which eventually shows two options. Select the ‘Project Settings‘ option. You should see the below screen:

Scroll down to the ‘Your apps‘ section and download the ‘google-services.json‘ file. When prompted, enter your app’s package name. It’s important to enter the package name your app is using; this can only be set when you add the app to your Firebase project. Place your downloaded file in the ‘app‘ folder (just for example) root level to the ‘build.gradle‘ as shown in the below screenshot:

 

Now, add the dependency of the firebase in your project/build.gradle file as follows:

buildscript {
    ext.kotlin_version = "1.3.20"
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath "com.android.tools.build:gradle:3.3.0"
        classpath "com.google.gms:google-services:4.2.0"
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        google()
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

Add the Cloud Firestore Android library to your app/build.gradle file:

implementation 'com.google.firebase:firebase-firestore:17.1.5'

I personally recommend to add Firebase Core in your app/build.gradle file, to access all :

implementation 'com.google.firebase:firebase-core:16.0.6'

Now Sync the gradle and build the project.

Congratulations! You have now successfully integrated the Firebase and Firestore in your project. Let’s study closely how to we can dwell with Firestore in the next series of steps.

Get Started

Initiate the Firebase Firestore instance in the your main activity:

val db = FirebaseFirestore.getInstance()

 

Let us create a new collection “users” which contains “user” documents. Run the following piece of code to add a collection:

val user = HashMap<String, Any>()
        user["firstName"] = "Dinesh"
        user["lastName"] = "Merugumilli"
        // Add a new document with a generated ID
        db.collection("users")
                .add(user)
                .addOnSuccessListener { documentReference ->
                    Log.d(TAG, "DocumentSnapshot added with ID: " + documentReference.id)
                    //Show Dialog with success response
                    showDialog("Fantastic",
                            "Success!! A new record inserted into the existing one!")
                }
                .addOnFailureListener { e ->
                    Log.w(TAG, "Error adding document", e)
                    //Show Dialog with a failure message
                    showDialog("Oops",
                            "Error!! Fail to create / insert a new document !")
                }

 

Note:

  • If there is no collection with a name “users” then it will create a new one. For existing collection, it will update.
  • Also, make sure your rules in the cloud firestore are allowing you to do changes.

 

If you visit your firebase console and to go the project, you should see the Firestore database with “users” collection and “user’ document. For example as below screenshot:

To update a record in the “users” collection, let us set user to the document. If user not exists, a new record will be created in the document.

 val user = HashMap<String, Any>()
        user["firstName"] = firstname.text.toString()
        user["lastName"] = lastname.text.toString()

        db.collection("users").document("user")
                .set(user, SetOptions.merge())
                .addOnSuccessListener {
                    Log.d(TAG, "DocumentSnapshot successfully written!")
                    showDialog("Fantastic",
                            "Nicely done. A new record merged into the existing one!")
                }
                .addOnFailureListener { e ->
                    Log.w(TAG, "Error writing document", e)
                    showDialog("Oh Fuck!",
                            "Something screwed buddy. Have a look at your piece of fucking code!!!")
                }

Now, let’s retrieve data from the database. We will go for complex queries in the text tutorial. A simple get() will do the magic here:

db.collection("users").document("user")
                .get()
                .addOnSuccessListener { document ->
                    if (document != null) {

                        showDialog("Fantastic", String.format("%s \n\n %s"
                                , "Nicely done. All records retrieved below, have a look: "
                                , document.data))
                    } else {

                        showDialog("Oh Fuck!",
                                "There is no such document. Have a look at your piece of fucking code!!!")
                    }

                }
                .addOnFailureListener { e ->
                    Log.w(TAG, "Error writing document", e)
                    showDialog("Oh Fuck!",
                            "Something screwed buddy. Have a look at your piece of fucking code!!!")
                }

See the below screenshot as the result of the above code:

Now, deleting a document. We can also delete the data in the document with querying Firestore.

 db.collection("users").document("user")
                .delete()
                .addOnSuccessListener {
                    showDialog("Fantastic",
                            "Nicely done. You have successfully deleted the document!!")
                }
                .addOnFailureListener { e ->
                    showDialog("Oh God!",
                            "Something screwed buddy. Have a look at your piece of code!!!")
                }

Please also go through the screenshot below:

Leave a Reply

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

Post comment