X

Android Firebase Database Tutorial

 

Android firebase database

Firebase cloud storage is the best option to  make a app on android firebase realtime database for the beginners.There is no server side script involved in this process so on any basis its simple and easier to start.

Making use of firebase services is advisory as its providing a free service based on the usage* and is providing a efficient and reliable service so i recommend you to choose it when there is suitable requirement for you not only database firebase offer ‘s various service which you can find here.

Also you can find the relevant video tutorials to get more in-depth knowledge regarding the topic we are dealing with.

We will provide the complete details in this blog and also video tutorials provided for the easier understanding.

 

Android firebase database video tutorial :

If you are facing any trouble in adding firebase to your account may refer to

 

 

Project Structure :

The project structure of android firebase database is shown in this image.

 

Dependency :

Make sure you find the latest version of dependency’s before proceeding further to avoid deprecated classes and thereby errors.

build.gradle (Project: FirebaseDatabase)

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

 

build.gradle (Module: App)

apply plugin: 'com.google.gms.google-services'
implementation 'com.google.firebase:firebase-database-ktx:19.3.0'

 

Rules :

I have made rules public just for this tutorial you may make them private

{
"rules": {
".read": true,
".write": true
}
}

 

for private, default, user rules refer

 

activity_main.xml

Add a edittext, button and text view to display fetched data.

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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">

    <EditText
        android:id="@+id/edt_input"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="50dp"
        android:hint="message"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/btn_submit"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="48dp"
        android:text="submit"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.755"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/edt_input" />

    <TextView
        android:id="@+id/txt_display"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

 

MainActivity.class

Create an object for android firebase database reference

lateinit var myRef : DatabaseReference

database object

val database = Firebase.database

 

setting key  for data

myRef = database.getReference("message")

 

setting value for the key

myRef.setValue("Androidcoding.in")

 

Can find the screen below showing the data inserted using key value attributes in android firebase database.

 

listener to handle task success and  failure states

myRef.addValueEventListener(object : ValueEventListener {
    override fun onDataChange(dataSnapshot: DataSnapshot) {
        // This method is called once with the initial value and again
        // whenever data at this location is updated.
        val value = dataSnapshot.getValue()

        txt_display.setText("Value is: $value")
    }

    override fun onCancelled(error: DatabaseError) {
        // Failed to read value
        Log.w("Status", "Failed to read value.", error.toException())
    }
})

 

For better practice use view binding’s may find more information here

import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import com.google.firebase.database.DataSnapshot
import com.google.firebase.database.DatabaseError
import com.google.firebase.database.DatabaseReference
import com.google.firebase.database.ValueEventListener
import com.google.firebase.database.ktx.database
import com.google.firebase.ktx.Firebase
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() ,View.OnClickListener{

    lateinit var myRef : DatabaseReference

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // Write a message to the database
        val database = Firebase.database

        myRef = database.getReference("message")

        myRef.setValue("Androidcoding.in")

        btn_submit.setOnClickListener(this)

        // Read from the database
        myRef.addValueEventListener(object : ValueEventListener {
            override fun onDataChange(dataSnapshot: DataSnapshot) {
                // This method is called once with the initial value and again
                // whenever data at this location is updated.
                val value = dataSnapshot.getValue()

                txt_display.setText("Value is: $value")
            }

            override fun onCancelled(error: DatabaseError) {
                // Failed to read value
                Log.w("Status", "Failed to read value.", error.toException())
            }
        })
    }

    override fun onClick(v: View?) {
        when(v!!.id){

            R.id.btn_submit -> {
                myRef.setValue(edt_input.text.toString())
            }
        }
    }
}

 

Android firebase database output :

The screen depicts android firebase database

 

If there are any query’s in this tutorial on android firebase database do let us know in the comment section below and also like share this tutorial to get more interesting updates.

abhishek:
Related Post

This website uses cookies.