- Firebase realtime database android kotlin
- Step-by-Step Implementation
- Output
- AK Bonus Points
- HOW TO USE FIREBASE REALTIME DATABASE IN ANDROID/Kotlin
- Our Example
- Steps
- 1) Create Realtime Database and data node in Firebase.
- 2) Integrate and Code Firebase Realtime Database in your app
- Whole Code
- 3) Run and test your app
- Conclusion
- Connect your App to Firebase
- Add the Realtime Database SDK to your app
- Kotlin+KTX
- Java
- Configure Realtime Database Security Rules
- Write to your database
- Kotlin+KTX
- Java
- Read from your database
- Kotlin+KTX
- Java
- Optional: Configure ProGuard
- Prepare for Launch
- Next Steps
Firebase realtime database android kotlin
Firebase is a service to applications, it provides hosting, NoSQL storage, real-time databases, social authentication, notification, and other services.
In this project, we have created a login and signup page in android studio using firebase realtime database so all our data will be saved for free! When the user signs up using a username and password gets stored in the realtime database of firebase.
For login purposes, the same credentials are checked in the firebase realtime database and if it matches with user credentials then it will lead you to the home screen otherwise it will throw an error as login failed.
Step-by-Step Implementation
Step 1: Open Android Studio, Click New Project and Choose Empty Activity.
Step 2:colors.xml
#FFBB86FC #FF6200EE #FF3700B3 #FF03DAC5 #FF018786 #FF000000 #FFFFFFFF #8692f7
AndroidManifest.xml
lavender_border.xml
buildFeatures < viewBinding true >implementation 'com.github.bumptech.glide:glide:4.14.2' annotationProcessor 'com.github.bumptech.glide:compiler:4.14.2'
progress_layout.xml
Step 3: activity_main.xml
Step 4: activity_upload.xml
recycler_item.xml
Step 5: MainActivity.kt
package com.example.storerealkot import android.content.Intent import android.os.Bundle import android.view.View import androidx.appcompat.app.AlertDialog import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.widget.SearchView import androidx.recyclerview.widget.GridLayoutManager import com.example.storerealkot.databinding.ActivityMainBinding import com.google.firebase.database.* import java.util.* class MainActivity : AppCompatActivity() < var databaseReference: DatabaseReference? = null var eventListener: ValueEventListener? = null private lateinit var dataList: ArrayListprivate lateinit var adapter: MyAdapter private lateinit var binding: ActivityMainBinding override fun onCreate(savedInstanceState: Bundle?) < super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) val gridLayoutManager = GridLayoutManager(this@MainActivity, 1) binding.recyclerView.layoutManager = gridLayoutManager binding.search.clearFocus() val builder = AlertDialog.Builder(this@MainActivity) builder.setCancelable(false) builder.setView(R.layout.progress_layout) val dialog = builder.create() dialog.show() dataList = ArrayList() adapter = MyAdapter(this@MainActivity, dataList) binding.recyclerView.adapter = adapter databaseReference = FirebaseDatabase.getInstance().getReference("Todo List") dialog.show() eventListener = databaseReference. addValueEventListener(object : ValueEventListener < override fun onDataChange(snapshot: DataSnapshot) < dataList.clear() for (itemSnapshot in snapshot.children) < val dataClass = itemSnapshot.getValue(DataClass::class.java) if (dataClass != null) < dataList.add(dataClass) >> adapter.notifyDataSetChanged() dialog.dismiss() > override fun onCancelled(error: DatabaseError) < dialog.dismiss() >>) binding.fab.setOnClickListener(View.OnClickListener < val intent = Intent(this@MainActivity, UploadActivity::class.java) startActivity(intent) >) binding.search.setOnQueryTextListener(object : SearchView.OnQueryTextListener < override fun onQueryTextSubmit(query: String): Boolean < return false >override fun onQueryTextChange(newText: String): Boolean < searchList(newText) return true >>) > fun searchList(text: String) < val searchList = java.util.ArrayList() for (dataClass in dataList) < if (dataClass.dataTitle?.lowercase() ?.contains(text.lowercase(Locale.getDefault())) == true ) < searchList.add(dataClass) >> adapter.searchDataList(searchList) > >
Step 6: DataClass.kt
package com.example.todolist class DataClass < var dataTitle: String? = null var dataDesc: String? = null var dataPriority: String? = null var dataImage: String? = null constructor(dataTitle: String?, dataDesc: String?, dataPriority: String?, dataImage: String?)< this.dataTitle = dataTitle this.dataDesc = dataDesc this.dataPriority = dataPriority this.dataImage = dataImage >constructor() <> >
Step 7: UploadActivity.kt
package com.example.todolist import android.content.Intent import android.net.Uri import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.Toast import androidx.activity.result.ActivityResult import androidx.activity.result.contract.ActivityResultContracts import androidx.appcompat.app.AlertDialog import com.example.todolist.databinding.ActivityUploadBinding import com.google.firebase.database.FirebaseDatabase import com.google.firebase.storage.FirebaseStorage import java.net.URI import java.text.DateFormat import java.util.Calendar class UploadActivity : AppCompatActivity() < private lateinit var binding: ActivityUploadBinding var imageURL: String? = null var uri: Uri? = null override fun onCreate(savedInstanceState: Bundle?) < super.onCreate(savedInstanceState) binding = ActivityUploadBinding.inflate(layoutInflater) setContentView(binding.root) val activityResultLauncher = registerForActivityResult( ActivityResultContracts.StartActivityForResult()) < result ->if (result.resultCode == RESULT_OK) < val data = result.data uri = data. data binding.uploadImage.setImageURI(uri) >else < Toast.makeText(this@UploadActivity, "No Image Selected", Toast.LENGTH_SHORT).show() >> binding.uploadImage.setOnClickListener < val photoPicker = Intent(Intent.ACTION_PICK) photoPicker.type = "image/*" activityResultLauncher.launch(photoPicker) >binding.saveButton.setOnClickListener < saveData() >> private fun saveData() < val storageReference = FirebaseStorage.getInstance().reference.child("Task Images") .child(uri. lastPathSegment!!) val builder = AlertDialog.Builder(this@UploadActivity) builder.setCancelable(false) builder.setView(R.layout.progress_layout) val dialog = builder.create() dialog.show() storageReference.putFile(uri!!).addOnSuccessListener < taskSnapshot ->val uriTask = taskSnapshot.storage.downloadUrl while (!uriTask.isComplete); val urlImage = uriTask.result imageURL = urlImage.toString() uploadData() dialog.dismiss() >.addOnFailureListener < dialog.dismiss() >> private fun uploadData() < val title = binding.uploadTitle.text.toString() val desc = binding.uploadDesc.text.toString() val priority = binding.uploadPriority.text.toString() val dataClass = DataClass(title, desc, priority, imageURL) val currentDate = DateFormat.getDateTimeInstance().format(Calendar.getInstance().time) FirebaseDatabase.getInstance().getReference("Todo List").child(currentDate) .setValue(dataClass).addOnCompleteListener < task ->if (task.isSuccessful) < Toast.makeText(this@UploadActivity, "Saved", Toast.LENGTH_SHORT).show() finish() >>.addOnFailureListener < e ->Toast.makeText( this@UploadActivity, e.message.toString(), Toast.LENGTH_SHORT).show() > > >
Step 8: MyAdapter.kt
package com.example.storerealkot import android.content.Context import android.content.Intent import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.TextView import androidx.cardview.widget.CardView import androidx.recyclerview.widget.RecyclerView import com.bumptech.glide.Glide class MyAdapter(private val context: Context, private var dataList: List) : RecyclerView.Adapter() < override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder < val view: View = LayoutInflater.from(parent.context).inflate(R.layout.recycler_item, parent, false) return MyViewHolder(view) >override fun onBindViewHolder(holder: MyViewHolder, position: Int) < Glide.with(context).load(dataList[position].dataImage) .into(holder.recImage) holder.recTitle.text = dataList[position].dataTitle holder.recDesc.text = dataList[position].dataDesc holder.recPriority.text = dataList[position].dataPriority holder.recCard.setOnClickListener < val intent = Intent(context, DetailActivity::class.java) intent.putExtra("Image", dataList[holder.adapterPosition].dataImage) intent.putExtra("Description", dataList[holder.adapterPosition].dataDesc) intent.putExtra("Title", dataList[holder.adapterPosition].dataTitle) intent.putExtra("Priority", dataList[holder.adapterPosition].dataPriority) context.startActivity(intent) >> override fun getItemCount(): Int < return dataList.size >fun searchDataList(searchList: List) < dataList = searchList notifyDataSetChanged() >> class MyViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) < var recImage: ImageView var recTitle: TextView var recDesc: TextView var recPriority: TextView var recCard: CardView init < recImage = itemView.findViewById(R.id.recImage) recTitle = itemView.findViewById(R.id.recTitle) recDesc = itemView.findViewById(R.id.recDesc) recPriority = itemView.findViewById(R.id.recPriority) recCard = itemView.findViewById(R.id.recCard) >>
package com.example.storerealkot import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import com.bumptech.glide.Glide import com.example.storerealkot.databinding.ActivityDetailBinding class DetailActivity : AppCompatActivity() < var imageUrl = "" private lateinit var binding: ActivityDetailBinding override fun onCreate(savedInstanceState: Bundle?) < super.onCreate(savedInstanceState) binding = ActivityDetailBinding.inflate(layoutInflater) setContentView(binding.root) val bundle = intent.extras if (bundle != null) < binding.detailDesc.text = bundle.getString("Description") binding.detailTitle.text = bundle.getString("Title") binding.detailPriority.text = bundle.getString("Priority") imageUrl = bundle.getString("Image")!! Glide.with(this).load(bundle.getString("Image")) .into(binding.detailImage) >> >
Output
AK Bonus Points
If you have any queries or errors, please feel free to comment below 🙂
Retrieve Data from Firebase Realtime Database in Android Studio using Kotlin:
HOW TO USE FIREBASE REALTIME DATABASE IN ANDROID/Kotlin
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:
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
1) Create Realtime Database and data node in Firebase.
2) Integrate and Code Firebase Realtime Database in 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.
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.
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)
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() >
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.
Connect your App to Firebase
When you enable Realtime Database, it also enables the API in the Cloud API Manager.
Add the Realtime Database SDK to your app
In your module (app-level) Gradle file (usually //build.gradle.kts or //build.gradle ), add the dependency for the Realtime Database Android library. We recommend using the Firebase Android BoM to control library versioning.
Kotlin+KTX
By using the Firebase Android BoM, your app will always use compatible versions of Firebase Android libraries.
(Alternative) Add Firebase library dependencies without using the BoM
If you choose not to use the Firebase BoM, you must specify each Firebase library version in its dependency line.
Note that if you use multiple Firebase libraries in your app, we strongly recommend using the BoM to manage library versions, which ensures that all versions are compatible.
Java
By using the Firebase Android BoM, your app will always use compatible versions of Firebase Android libraries.
(Alternative) Add Firebase library dependencies without using the BoM
If you choose not to use the Firebase BoM, you must specify each Firebase library version in its dependency line.
Note that if you use multiple Firebase libraries in your app, we strongly recommend using the BoM to manage library versions, which ensures that all versions are compatible.
Configure Realtime Database Security Rules
The Realtime Database provides a declarative rules language that allows you to define how your data should be structured, how it should be indexed, and when your data can be read from and written to.
Note: By default, read and write access to your database is restricted so only authenticated users can read or write data. To get started without setting up Authentication, you can configure your rules for public access. This does make your database open to anyone, even people not using your app, so be sure to restrict your database again when you set up authentication.
Write to your database
Retrieve an instance of your database using getInstance() and reference the location you want to write to.
Important: To get a reference to a database other than a us-central1 default database, you must pass the database URL to getInstance() (or for Kotlin+KTX database() ). For a us-central1 default database, you can call getInstance() (or database ) without arguments.
You can find your Realtime Database URL in the Realtime Database section of the Firebase console. Depending on the location of the database, the database URL will be in one of the following forms:
Kotlin+KTX
Java
You can save a range of data types to the database this way, including Java objects. When you save an object the responses from any getters will be saved as children of this location.
Read from your database
To make your app data update in realtime, you should add a ValueEventListener to the reference you just created. The onDataChange() method in this class is triggered once when the listener is attached and again every time the data changes, including the children.
Kotlin+KTX
Java
Optional: Configure ProGuard
When using Firebase Realtime Database in your app along with ProGuard, you need to consider how your model objects will be serialized and deserialized after obfuscation. If you use DataSnapshot.getValue(Class) or DatabaseReference.setValue(Object) to read and write data, you will need to add rules to the proguard-rules.pro file:
# Add this global rule -keepattributes Signature # This rule will properly ProGuard all the model classes in # the package com.yourcompany.models. # Modify this rule to fit the structure of your app. -keepclassmembers class com.yourcompany.models.**
To get help for questions or issues related to ProGuard, visit the Guardsquare Community forums to get assistance from an expert.
Prepare for Launch
Before launching your app, we recommend walking through our launch checklist to make sure your app is ready to go! Be sure to enable App Check to help ensure that only your apps can access your databases.
Next Steps
Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.
Last updated 2023-07-18 UTC.