HOW TO USE FIREBASE REALTIME DATABASE IN ANDROID/Kotlin

Share Post
  •  
  •  
  •  
  • 1
  •  
  •  
  •  
  •  
  •  
  •  
  •  
    1
    Share

Please Subscribe Youtube| Like Facebook | Follow Twitter

For Java follow this article

Introduction

In this article we will learn how to use firebase real time database in our app. The Firebase Realtime Database is a cloud-hosted database. Data is stored as JSON and synchronized in realtime to every connected client and remains available when your app goes offline.

Our Example

In our example we have textview “data” which displays/reads current value of realtime database node named “data”. We also have an edittext “change_data” which allows users to change value of data node at realtime db on a “change” button click, after changing its value in realtime database corresponding value will also be reflected inside “data” textview of all connected users.

Requirements:

  1. Android Project/App in which Realtime Database to be implemented
  2. Firebase Project

Note: First you need to create Firebase Project and then connect your app to it. You can follow this article to set it up.

Steps

Follow below steps

1) Create Realtime Database and data node in Firebase.

2) Integrate and Code Firebase Realtime Database in your app

3) Run and test your app

1) Create Realtime Database and data node in Firebase.

First go to Firebase and open your Firebase Project and click on Database and then click on Create Database under Realtime Database Heading.

Start in test mode during testing, which allows anyone who have your db reference to read and write data to your database. During real time development or production impose security rules by using firebase authentication according to your requirements

After creating Database, create a node named data and assign its value “default”

2) Integrate and Code Firebase Realtime Database in your app

First add firebase realtime database library at app level build.gradle file

implementation 'com.google.firebase:firebase-database:19.3.0'

Layout file conatins textview, edittext and button below is xml code.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:orientation="vertical"
    >

    <TextView
        android:id="@+id/data"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:text="Value is : "
        android:gravity="center"
        />
    <EditText
        android:id="@+id/changeData"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:text=""
        android:hint="Change Data"
        android:gravity="center"
        />
    <Button
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="0.5"
        android:text="change"
        android:onClick="change"
        />

</LinearLayout>

Inside oncreate() method we have first created Firebase Realtime Database object inside db varaiable and got reference to data node inside dataNodeRef varaiable. dataNodeRef variable corresponds to data node inside firebase database which we have created in first step.

db = FirebaseDatabase.getInstance()
dataNodeRef = db!!.getReference("data")

addValueEventListener is added to dataNodeRef, which will call onDataChange() whenever dataNodeRef(data) value is changed. Inside onDataChange() we will set that value to our data textview.

dataNodeRef!!.addValueEventListener(object : ValueEventListener {
	override fun onDataChange(dataSnapshot: DataSnapshot) {
		if (dataSnapshot.exists()) data.text = "Value is : " + dataSnapshot.value
	}

	override fun onCancelled(databaseError: DatabaseError) {}
})

change() method will be called when change button is clicked. It will get current value of our change_data edittext and set that value to our dataNodeRef(data). Thus dataNodeRef(data) value can be changed by any user by clicking change button and its value will be synced across all our connected user and will be displayed inside data textview as well inside data node of firebase database.

fun change(view: View?) {
	dataNodeRef!!.setValue(changeData.text.toString())
	changeData.setText("")
}

Whole Code

Project level build.gradle

buildscript {
    ext.kotlin_version = '1.4.0-rc'
    repositories {
        jcenter()
        google()
        maven { url 'https://dl.bintray.com/kotlin/kotlin-eap' }
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.5.3'
        // Add this line
        classpath 'com.google.gms:google-services:4.3.3'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    }
}

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

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

App level build.gradle

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'kotlin-android'
// Add this line
apply plugin: 'com.google.gms.google-services'
android {
    compileSdkVersion 28
    buildToolsVersion "29.0.3"
    defaultConfig {
        applicationId "com.programtown.example"
        minSdkVersion 17
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'androidx.appcompat:appcompat:1.0.2'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.ext:junit:1.1.0'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1'

    implementation 'com.google.firebase:firebase-database:19.3.0'
    implementation "androidx.core:core-ktx:1.3.1"
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
}
repositories {
    maven { url 'https://dl.bintray.com/kotlin/kotlin-eap' }
    mavenCentral()
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:orientation="vertical"
    >

    <TextView
        android:id="@+id/data"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:text="Value is : "
        android:gravity="center"
        />
    <EditText
        android:id="@+id/changeData"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:text=""
        android:hint="Change Data"
        android:gravity="center"
        />
    <Button
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="0.5"
        android:text="change"
        android:onClick="change"
        />

</LinearLayout>

MainActivity.kt

package com.programtown.example

import android.os.Bundle
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import com.google.firebase.database.*
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

    var db: FirebaseDatabase? = null
    var dataNodeRef: DatabaseReference? = null

    override fun onCreate(savedInstanceState: Bundle?) {

        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        db = FirebaseDatabase.getInstance()
        dataNodeRef = db!!.getReference("data")
        dataNodeRef!!.addValueEventListener(object : ValueEventListener {
            override fun onDataChange(dataSnapshot: DataSnapshot) {
                if (dataSnapshot.exists()) data.text = "Value is : " + dataSnapshot.value
            }

            override fun onCancelled(databaseError: DatabaseError) {}
        })
    }

    fun change(view: View?) {
        dataNodeRef!!.setValue(changeData.text.toString())
        changeData.setText("")
    }
}

3) Run and test your app

On first app launch initially value of data textview will be default.

After changing edittext value to “New value” and clicking on change button, data textview value as well as realtime database node data value will be changed to “New value”.

And this newly updated value will be synced/visible to all our connected user of our application.

Conclusion

So in this post we have learned how to integrate/connect Firebase Real Time Database in android application.

Please Subscribe Youtube| Like Facebook | Follow Twitter


Share Post
  •  
  •  
  •  
  • 1
  •  
  •  
  •  
  •  
  •  
  •  
  •  
    1
    Share

Leave a Reply

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