Firebase: Realtime Database Reading and Writing FIREBASE

Firebase: Realtime Database Reading and Writing  

Firebase: Realtime Database Reading and Writing

Firebase: Realtime Database Reading and Writing

In the previous section(Firebase: Data Organization in Real-time Database), we created an android application and added Firebase with it. We have already implemented all the required libraries and plugins also. There is a database that we have created before naming fir-realtimedatabaseexam-60676.

   

Writing into Database

Inside your code, we have to retrieve an instance of our database using getInstance() method and then reference the location we have to write to. You have to remember that the database is organized around JSON nodes.

And attach an asynchronous listener to the reference. The listener is triggered one time for the initial state of the data, and again any time when the data changes.

  1. Private lateinit var database:DatabaseReference  
  2. //??.  
  3. Database=FirebaseDatabase.getInstance().reference  
  4. myRef=database.getReference("message")  
  5.   
  6. myRef.setValue("Hello,World!")  

You can save a range of data types (String, Long, Double, and Boolean, etc.) of the database. In this way, we can save Kotlin objects. When you save an object, the responses from any getters will be saved as children of this location and JSON format.

A class that defines the user as a custom java object carries a default constructor that takes no arguments and has public getters for the properties to be assigned.

Writing an object (User.kt, Signing.kt)

We will write an actual object, which is the user object. The user in our User.kotlin class and Signing or register activity write that object. So, when we use the Kotlin object, the contents of our object are automatically mapped to the child location in a nested fashion. Using the object, we make our code more readable and easier to maintain and good to write the object.

  1. data class User(  
  2.      var username:String?=null,  
  3.      var email:String?=null  
  4. )  

 We can add user object with setVaue() function

  1. private fun writeNewUser(userId:String, name:String,email:String?)){  
  2.      val user=User(name,email)  
  3.      database.child("users").child(userId).setValue(user)  
  4. }  

You can use the set value method to write a new user. You can still update a child without rewriting the entire object.

databse.child("users").child(userId).child("username").setValue(name)  

 

Reading into Database

To read data at a path and to listen for any changes if the data changes, we have to use the addValueEventListener() or addListenerForSingleValueEvent() method to add a ValueEventListener to a database reference. These two methods will add a valueEventListener to a DatabaseReference. 

You can use the onDataChange() method to read a static snapshot of the contents on a given path. It is triggered once when the listener is attached and again every time the data changes, including the children. It passes a snapshot containing all the data at the location, including child data. If there is no data, the snapshot will return false when we call exists() and null when we call getValue()

In a few cases, we may want a callback to be called once and then immediately removed. It is useful for data that only needs to be loaded once and is not expected to change frequently or require active listening. Listening does have some overhead, so if we only need to read it once, we don't need to do the callback.

For example, when initializing user interface elements that you don't expect to change, but we want to use the addListenerForSingleValueEvent() only when you need to read one part of the data. It doesn't change a law once and only once.

Example:

We are implementing an android application. It is a user logging and registration application that has three XML files and four Kotlin files. The activity_main.xml is used for the registration page. The activity_signing.xml is used for login, and activity_welcome.xml is used for data retrieving from the database. Similarly, there is four Kotlin file, i.e., MainActivity, Signing, welcome, and User.

When the users register themselves, they are added into the firebase console user section, and the data corresponding them is stored into the database. The signing functionality is the same as we have done in our authentication section. When a user successfully registers or sign-up, he will switch to the welcome page where he found his data.

activity_main.xml, activity_signing, and activity_welcome

MainActivity.kt

  1. package com.example.firebaserealtimedatabase  
  2.   
  3. import android.content.Intent  
  4. import androidx.appcompat.app.AppCompatActivity  
  5. import android.os.Bundle  
  6. import android.text.TextUtils  
  7. import android.util.Log  
  8. import android.view.View  
  9. import android.widget.Toast  
  10. import com.google.firebase.auth.FirebaseAuth  
  11. import com.google.firebase.database.DatabaseReference  
  12. import com.google.firebase.database.FirebaseDatabase  
  13. import kotlinx.android.synthetic.main.activity_main.*  
  14.   
  15. class MainActivity : AppCompatActivity() {  
  16.       
  17.     //Creating member variables of FirebaseAuth  
  18.     private var mAuth: FirebaseAuth?=null  
  19.   
  20.     //Creating member variables of FirebaseDatabase and DatabaseReference  
  21.     private var mFirebaseDatabaseInstances: FirebaseDatabase?=null  
  22.     private var mFirebaseDatabase: DatabaseReference?=null  
  23.   
  24.     //Creating member variable for userId and emailAddress  
  25.     private var userId:String?=null  
  26.     private var emailAddress:String?=null  
  27.   
  28.     override fun onCreate(savedInstanceState: Bundle?) {  
  29.         super.onCreate(savedInstanceState)  
  30.         setContentView(R.layout.activity_main)  
  31.   
  32.         //Get Firebase Instances  
  33.         mAuth=FirebaseAuth.getInstance()  
  34.   
  35.         //Get instance of FirebaseDatabase  
  36.         mFirebaseDatabaseInstances= FirebaseDatabase.getInstance()  
  37.   
  38.         //if already logged in go to sign in screen  
  39.         if(mAuth!!.currentUser!=null){  
  40.             startActivity(Intent(this,welcome::class.java))  
  41.             finish()  
  42.         }  
  43.     }  
  44.   
  45.     fun onLoginClicked(view: View) {  
  46.         startActivity(Intent(this,Signing::class.java))  
  47.         finish()  
  48.     }  
  49.     //calling onRegisterClicked button  
  50.     fun onRegisterClicked(view: View) {  
  51.          //Validation checking  
  52.         if(TextUtils.isEmpty(username.text.toString())){  
  53.             Toast.makeText(applicationContext,"Enter Username!",Toast.LENGTH_LONG).show()  
  54.         }  
  55.         if(TextUtils.isEmpty(email.text.toString())){  
  56.             Toast.makeText(applicationContext,"Enter email address!",Toast.LENGTH_LONG).show()  
  57.         }  
  58.         if(TextUtils.isEmpty(password.text.toString())){  
  59.             Toast.makeText(applicationContext,"Enter password!",Toast.LENGTH_LONG).show()  
  60.         }  
  61.         if(password.text.toString().length<6){  
  62.             Toast.makeText(applicationContext,"Password is too short",Toast.LENGTH_LONG).show()  
  63.         }  
  64.         //Making progressBar visible  
  65.         progressBar!!.visibility=View.VISIBLE  
  66.   
  67.         //creating user  
  68.         mAuth!!.createUserWithEmailAndPassword(email.text.toString(),password.text.toString())  
  69.             .addOnCompleteListener(this){task ->  
  70.                 Toast.makeText(this,"createUserWithEmail:onComplete"+task.isSuccessful,Toast.LENGTH_SHORT).show()  
  71.                 progressBar.visibility=View.GONE  
  72.                   
  73.                 // When the sign-in is failed, a message to the user is displayed. If the sign-in is successful, auth state listener will get notified, and logic to handle the signed-in user can be handled in the listener.   
  74.                 if(task.isSuccessful){  
  75.                       
  76.                     //Getting reference to ?users? node  
  77.                     mFirebaseDatabase=mFirebaseDatabaseInstances!!.getReference("users")  
  78.                       
  79.                     //Getting current user from FirebaseAuth   
  80.                     val user=FirebaseAuth.getInstance().currentUser  
  81.   
  82.                     //add username, email to database  
  83.                     userId=user!!.uid  
  84.                     emailAddress=user.email  
  85.   
  86.                     //Creating a new user  
  87.                     val myUser=User(username.text.toString(),emailAddress!!)  
  88.                
  89.                      //Writing data into database using setValue() method  
  90.                     mFirebaseDatabase!!.child(userId!!).setValue(myUser)  
  91.   
  92.                     startActivity(Intent(this,welcome::class.java))  
  93.                     finish()  
  94.                 }else{  
  95.                     Toast.makeText(this,"Authentication Failed"+task.exception,Toast.LENGTH_SHORT).show()  
  96.                     Log.e("MyTag",task.exception.toString())  
  97.                 }  
  98.             }  
  99.     }  
  100. }  

 

welcome.kt

 
  1. package com.example.firebaserealtimedatabase  
  2.   
  3. import android.content.Intent  
  4. import android.nfc.Tag  
  5. import androidx.appcompat.app.AppCompatActivity  
  6. import android.os.Bundle  
  7. import android.util.Log  
  8. import android.view.View  
  9. import androidx.constraintlayout.solver.widgets.Snapshot  
  10. import com.google.firebase.auth.FirebaseAuth  
  11. import com.google.firebase.database.*  
  12. import kotlinx.android.synthetic.main.activity_main.*  
  13.   
  14. class welcome : AppCompatActivity() {  
  15.   
  16.     //Creating member variables  
  17.     private var mFirebaseDatabase: DatabaseReference?=null  
  18.     private var mFirebaseInstance: FirebaseDatabase?=null  
  19.   
  20.     var userId:String?=null  
  21.   
  22.     override fun onCreate(savedInstanceState: Bundle?) {  
  23.         super.onCreate(savedInstanceState)  
  24.         setContentView(R.layout.activity_welcome)  
  25.   
  26.         //Getting instances of FirebaseDatabase  
  27.         mFirebaseInstance= FirebaseDatabase.getInstance()  
  28.   
  29.         //get reference to 'users' node  
  30.         mFirebaseDatabase=mFirebaseInstance!!.getReference("users")  
  31.   
  32.         val user=FirebaseAuth.getInstance().currentUser  
  33.   
  34.         //add it only if it is not saved to database  
  35.         if (user != null) {  
  36.             userId=user.uid  
  37.         }  
  38.         addUserChangeListener()  
  39.     }  
  40.     private fun addUserChangeListener(){  
  41.           
  42.         //User data change Listener  
  43.         mFirebaseDatabase!!.child(userId!!).addValueEventListener(object: ValueEventListener{  
  44.             override fun onDataChange(dataSnapshot: DataSnapshot){  
  45.                 val user=dataSnapshot.getValue(User::class.java)  
  46.   
  47.                 //Check for null  
  48.                 if(user==null){  
  49.                     Log.e(TAG,"User data is null")  
  50.                     return  
  51.                 }  
  52.                 Log.e(TAG,"User data is changed!"+user.name+","+user.email)  
  53.   
  54.                 //Display newly updated name and email  
  55.                 email.setText(user.email)  
  56.                 username.setText(user.name)  
  57.   
  58.   
  59.             }  
  60.             override fun onCancelled(error: DatabaseError){  
  61.                 //Failed to read value  
  62.                 Log.e(TAG,"Failed to read user",error.toException())  
  63.             }  
  64.         })  
  65.     }  
  66.     fun onLogout(view: View) {  
  67.         FirebaseAuth.getInstance().signOut()  
  68.         startActivity(Intent(this, MainActivity::class.java))  
  69.     }  
  70.     companion object{  
  71.         private val TAG=database::class.java.simpleName  
  72.     }  
  73. }  

 

User.kt

  1. package com.example.firebaserealtimedatabase  
  2.   
  3. import androidx.appcompat.app.AppCompatActivity  
  4. import android.os.Bundle  
  5.   
  6. class User{  
  7.   
  8.     lateinit var name:String  
  9.     lateinit var email:String  
  10.   
  11.     //Default constructor required for calls to  
  12.     //DataSnapshot.getValue(User.class)  
  13.     constructor(){  
  14.   
  15.     }  
  16.   
  17.     constructor(name:String,email:String){  
  18.         this.name=name  
  19.         this.email=email  
  20.     }  
  21. }  
 

 

Signing.kt

  1. package com.example.firebaserealtimedatabase  
  2.   
  3. import android.content.Intent  
  4. import androidx.appcompat.app.AppCompatActivity  
  5. import android.os.Bundle  
  6. import android.text.TextUtils  
  7. import android.util.Log  
  8. import android.view.View  
  9. import android.widget.Toast  
  10. import com.google.firebase.auth.FirebaseAuth  
  11. import kotlinx.android.synthetic.main.activity_main.*  
  12.   
  13. class Signing : AppCompatActivity() {  
  14.   
  15.     private var mAuth: FirebaseAuth?=null  
  16.   
  17.     override fun onCreate(savedInstanceState: Bundle?) {  
  18.         super.onCreate(savedInstanceState)  
  19.         setContentView(R.layout.activity_signing)  
  20.   
  21.         //Initialize Firebase Auth  
  22.         mAuth=FirebaseAuth.getInstance()  
  23.     }  
  24.   
  25.     public override fun onStart() {  
  26.         super.onStart()  
  27.   
  28.         //if user logged in, go to sign in screen  
  29.         if(mAuth!!.currentUser!=null){  
  30.             startActivity(Intent(this,welcome::class.java))  
  31.             finish()  
  32.         }  
  33.     }  
  34.   
  35.     override fun onResume() {  
  36.         super.onResume()  
  37.         progressBar.visibility= View.GONE  
  38.     }  
  39.   
  40.     fun loginButtonClicked(view: View){  
  41.         if(TextUtils.isEmpty(email.text.toString())){  
  42.             Toast.makeText(applicationContext,"Enter Username!", Toast.LENGTH_LONG).show()  
  43.             return  
  44.         }  
  45.         if(TextUtils.isEmpty(password.text.toString())){  
  46.             Toast.makeText(applicationContext,"Enter password!", Toast.LENGTH_LONG).show()  
  47.             return  
  48.         }  
  49.         progressBar.visibility=View.VISIBLE  
  50.   
  51.         //Authenticate user  
  52.         mAuth!!.signInWithEmailAndPassword(email.text.toString(),password.text.toString())  
  53.             .addOnCompleteListener(this){task ->  
  54.   
  55.                 progressBar.visibility=View.GONE  
  56.   
  57.                 if(task.isSuccessful){  
  58.                     val intent=Intent(this,welcome::class.java)  
  59.                     startActivity(intent)  
  60.                     finish()  
  61.                 }else{  
  62.                     if(password.text.toString().length<6){  
  63.                         password.error="Password is too short, enter minimum 6 characters"  
  64.                     }  
  65.                     Toast.makeText(this,"Authentication Failed"+task.exception,Toast.LENGTH_SHORT).show()  
  66.                 }  
  67.             }  
  68.     }  
  69. }  
 

 

#askProgrammers
Learn Programming for Free


Join Programmers Community on Telegram


Talk with Experienced Programmers


Just drop a message, we will solve your queries