Authenticate your app using Firebase authentication and save user with data in Firebase Realtime Database

Ankit
Bobble Engineering
Published in
5 min readDec 19, 2022

In this blog, I am going to add an email-password authentication using the Firebase authentication service and then store the user's email and age in a real-time database. Later on, we can follow the same way to store sensitive data associated with users. There are different Firebase authentication ways other than email-password that we can use we will see them later in this blog.

Different Services offered by Firebase

Go to Android Studio and create a new project with an empty activity. In the top right corner, there is an icon to sign in to your google account, sign in first in order to use cloud functionality in your app. After signing in, it will show a SUCCESS message in the browser to get back to android studio. Now go to Tools -> Firebase -> Authentication -> Authenticate using a custom authentication system[Kotlin] Now follow the steps shown there, Click to Connect to Firebase, you will be redirected to firebase in the browser, click on add project and create a project there and add Connect. Hurray, your app is connected to firebase now follow the second step Add the firebase authentication SDK to your app and accept changes.

Now go to firebase console “console.firebase.google.com”, go to your project and select Authentication and now choose the sign-in method we want to use so select Email/Password, enable it and save.

Other sign-in providers

Now we will write our logic to user sign up, and login in to our mainActivity. The mainActivity XML contains one editText for email, one for the password, a Sign-Up button and a progress bar. Go through the code

class MainActivity : AppCompatActivity() {

private lateinit var email: EditText
private lateinit var password: EditText
private lateinit var signUp: Button
private lateinit var pb: ProgressBar
private lateinit var mAuth: FirebaseAuth

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

mAuth = FirebaseAuth.getInstance()
email = findViewById(R.id.email)
password = findViewById(R.id.password)
signUp = findViewById(R.id.signUp)
pb = findViewById(R.id.pb)
pb.visibility = View.INVISIBLE

signUp.setOnClickListener {
createUser()
}
}

override fun onStart() {
super.onStart()
//User is already loggedIn
if (mAuth.currentUser != null) {
startSuccessfulLoginActivity()
}
}

//Authentication using firebase Authentication
//Logic for Password, SignUp, Login
private fun createUser() {
val emailText = email.text.toString().trim()
val passwordText = password.text.toString().trim()

if (emailText.isEmpty()) {
email.error = "Email Required"
email.requestFocus()
return
}
if (!Patterns.EMAIL_ADDRESS.matcher(emailText).matches()) {
email.error = "Proper Email Required"
email.requestFocus()
return
}
if (passwordText.isEmpty() || passwordText.length <= 6) {
password.error = "Password Required with more than 6 characters"
password.requestFocus()
return
}

pb.visibility = View.VISIBLE
//if everything is fine email is correct and password is valid
//using instance of FirebaseAuth we will create the user
mAuth.createUserWithEmailAndPassword(emailText, passwordText)
.addOnCompleteListener(this) { task ->
if (task.isSuccessful) {
startSuccessfulLoginActivity()
} else {
if (task.exception is FirebaseAuthUserCollisionException) {
userLogin(emailText, passwordText)
} else {
pb.visibility = View.INVISIBLE
Toast.makeText(this, task.exception?.message, Toast.LENGTH_SHORT).show()
}
}
}
}

//if the user email is already exist in the list of Firebase Authentication "User"
//user will not be created again they will be logged in
private fun userLogin(emailText: String, passwordText: String) {
//here we uses signInWithEmailAndPassword function of FirebaseAuth
mAuth.signInWithEmailAndPassword(emailText, passwordText)
.addOnCompleteListener(this) { task ->
if (task.isSuccessful) {
startSuccessfulLoginActivity()
} else {
pb.visibility = View.INVISIBLE
Toast.makeText(this, task.exception?.message, Toast.LENGTH_SHORT).show()
}
}
}

private fun startSuccessfulLoginActivity() {
val intent = Intent(this, SaveUserInDB::class.java).apply {
flags = Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK
}
startActivity(intent)
}

}

Now our app gets authenticated, if we give proper credentials users will be created and we can check them in the Users section of Authentication of our project in the firebase console. Now we will use the Realtime Database of firebase to store users and some data. To do so go to Tools -> Firebase -> Realtime Database -> Get started with Realtime Database[Kotlin]. As we have already connected our project to Firebase we don't need to follow the first step just follow the second step Add the Realtime Database SDK to your app and accept the changes.

Now go to the firebase console and in our project select the Realtime Database and create database and in Security rules select the test mode as we want to see the data of the database. Go to the Rules section and modify it as

{
"rules": {
".read": "auth != null", // 2023-1-12
".write": "auth != null", // 2023-1-12
}
}

and publish. Then move to the Data section and hover on the HTTPS part select “+” and in the key write “Key” and tap on Add button. Now let's go to write the implementation to save data in our app. To create a new empty activity SaveUserInDB.kt in our project and add the following lines of code

class SaveUserInDB : AppCompatActivity() {

private lateinit var mAuth : FirebaseAuth
//In xml we have this edit text to take data input and a button to submit
private lateinit var et : EditText
private lateinit var btn : Button

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_save_user_in_db)
mAuth = FirebaseAuth.getInstance()
et = findViewById(R.id.et)
btn = findViewById(R.id.btn)
btn.setOnClickListener{
val data = et.text.toString()
saveData(data)
}
}

override fun onStart() {
super.onStart()
//User is LoggedOut send user to mainActivity to Login
if(mAuth.currentUser == null)
{
val intent = Intent(this,MainActivity::class.java).apply {
flags = Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK
}
startActivity(intent)
}
}

//Function to save data in Realtime Database of Firebase
private fun saveData(data: String) {
val email = mAuth.currentUser?.email
//Here UserInfo is a data class which tells DB that we have these columns
val user = email?.let { UserInfo(it,data) }

//Remember here we use keyword what we used in our Database i.e "Key"
//You can put anything at place of Key but same as your DataBase
val dbUsers = FirebaseDatabase.getInstance().getReference("Key")
dbUsers.child(mAuth.currentUser!!.uid)
.setValue(user).addOnCompleteListener(OnCompleteListener { task ->
if(task.isSuccessful){
Toast.makeText(this,"Token Saved", Toast.LENGTH_SHORT).show()
}
})
}
}

We also need to make a data class named UserInfo.kt which gives schema to our database

class UserInfo (
val email : String,
val age : String,
)

and now when we use our app and edit text we provide data, that data and the email of the user will be visible in the firebase console’s Realtime Database.

Note: Go through the code as it explains itself.

--

--