In this post, we will build a secure app with firebase authentication in kotlin. The app will register the user, log out the user, and also save and retrieve data for display on the main screen/ activity. Let's start
Step 1: Create a New android studio project with an empty activity.
Step 2: Add firebase to your android studio project and connect to the app.
Step 3: Setup firebase in the browser
Step 4: Add resource images for the user interface like Facebook, Google, and Twitter, and also create vectors in drawable for name, email, phone, and password watch the video for a full guide
Step 5: Add the following dependencies in the build.Gradle (module app)
dependencies {
implementation 'com.google.firebase:firebase-database:20.1.0'
implementation platform('com.google.firebase:firebase-bom:31.2.3')
implementation 'com.google.firebase:firebase-auth-ktx'
implementation 'com.google.firebase:firebase-firestore-ktx:23.0.2'
}
Step 6: Add the following dependencies in the build.Gradle (module project)
buildscript {
dependencies {
classpath 'com.google.gms:google-services:4.3.15'
}
}
Step 7: Create two new empty activities with the name LoginActivity and RegisterActivity. then shift the intent filter to register activity in a manifest file and do android:exported="true" > .
Step 8: Now add the following codes to respected activities
LoginActivity.kt
import android.app.Activity
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.ktx.auth
import com.google.firebase.ktx.Firebase
class LoginActivity : Activity() {
private lateinit var auth: FirebaseAuth
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_login)
// Initialize Firebase Auth
auth = Firebase.auth
super.onStart()
// Check if user is signed in (non-null) and update UI accordingly.
val currentUser = auth.currentUser
if(currentUser != null){
Toast.makeText(baseContext, "welcome back ",
Toast.LENGTH_SHORT).show()
val intent = Intent(this, MainActivity::class.java)
startActivity(intent)
}
val register = findViewById<Button>(R.id.rgbtn)
register.setOnClickListener {
val intent = Intent(this, RegisterActivity::class.java)
startActivity(intent)
}
val login = findViewById<Button>(R.id.loginbtn)
login.setOnClickListener {
val email = findViewById<EditText>(R.id.username)
val pass = findViewById<EditText>(R.id.passwordd)
val email1 = email.text.toString()
val password = pass.text.toString()
if (email.text.isEmpty() || pass.text.isEmpty()){
Toast.makeText(baseContext, "Please fill all fields", Toast.LENGTH_SHORT).show()
return@setOnClickListener
}
auth.signInWithEmailAndPassword(email1, password)
.addOnCompleteListener(this) { task ->
if (task.isSuccessful) {
// Sign in success, update UI with the signed-in user's information
Toast.makeText(baseContext, "success",
Toast.LENGTH_SHORT).show()
val intent = Intent(this, MainActivity::class.java)
startActivity(intent)
} else {
// If sign in fails, display a message to the user.
Toast.makeText(baseContext, "Authentication failed.",
Toast.LENGTH_SHORT).show()
}
}
.addOnFailureListener{
Toast.makeText(baseContext, "Authentication failed. ${it.localizedMessage}",
Toast.LENGTH_SHORT).show()
}
}
}
}
MainActivity.kt
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.ktx.auth
import com.google.firebase.firestore.FirebaseFirestore
import com.google.firebase.ktx.Firebase
class MainActivity : Activity() {
private lateinit var auth: FirebaseAuth
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
auth = Firebase.auth
val logout = findViewById<Button>(R.id.logout)
logout.setOnClickListener {
auth.signOut()
Toast.makeText(baseContext, "logged out",
Toast.LENGTH_SHORT).show()
val intent = Intent(this, LoginActivity::class.java)
startActivity(intent)
}
val user = auth.currentUser
if (user != null) {
val db = FirebaseFirestore.getInstance()
db.collection("users").document(user.uid)
.get()
.addOnSuccessListener { document ->
if (document != null) {
val name1 = user.displayName
val name = user.displayName
val phone = document.get("phone") as String
val userInfoTextView = findViewById<TextView>(R.id.name21)
userInfoTextView.text = "Welcome $name\n \n Your Phone Number Is: $phone"
}
}
.addOnFailureListener { exception ->
// Failed to retrieve user data
Toast.makeText(baseContext, "Failed to retrieve user data",
Toast.LENGTH_SHORT).show()
}
}
}
}
RegisterActivity.kt
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.UserProfileChangeRequest
import com.google.firebase.auth.ktx.auth
import com.google.firebase.firestore.FirebaseFirestore
import com.google.firebase.ktx.Firebase
class RegisterActivity : Activity() {
private lateinit var auth: FirebaseAuth
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_register)
// Initialize Firebase Auth
auth = Firebase.auth
val login = findViewById<Button>(R.id.lgbtn)
login.setOnClickListener {
val intent = Intent(this, LoginActivity::class.java)
startActivity(intent)
}
val register = findViewById<Button>(R.id.signupbtn)
register.setOnClickListener {
val email = findViewById<EditText>(R.id.email)
val pass = findViewById<EditText>(R.id.password)
val phone = findViewById<EditText>(R.id.phone)
val name = findViewById<EditText>(R.id.name)
val email1 = email.text.toString()
val password = pass.text.toString()
val phone1 = phone.text.toString()
val name1 = name.text.toString()
if (email.text.isEmpty() || pass.text.isEmpty() || phone.text.isEmpty()) {
Toast.makeText(baseContext, "Please fill all fields", Toast.LENGTH_SHORT).show()
return@setOnClickListener
}
auth.createUserWithEmailAndPassword(email1, password)
.addOnCompleteListener(this) { task ->
if (task.isSuccessful) {
// Sign in success, update UI with the signed-in user's information
Toast.makeText(baseContext, "success",
Toast.LENGTH_SHORT).show()
// val database = Firebase.database.reference
// val user = User(name1)
// database.child("users").child(usernamee).setValue(user)
auth = Firebase.auth
val user = auth.currentUser
val profileUpdates = UserProfileChangeRequest.Builder()
.setDisplayName(name1) // Set the name
.build()
user?.updateProfile(profileUpdates)
?.addOnCompleteListener { task ->
if (task.isSuccessful) {
// Name updated successfully
val intent = Intent(this, MainActivity::class.java)
startActivity(intent)
} else {
// Name update failed
}
}
val userUpdates = hashMapOf<String, Any>(
"phone" to phone1 // Set the phone number
)
val db = FirebaseFirestore.getInstance()
db.collection("users").document(user?.uid.toString())
.set(userUpdates)
.addOnSuccessListener { documentReference ->
// Phone number added successfully
}
.addOnFailureListener { e ->
// Phone number addition failed
}
} else {
// If sign in fails, display a message to the user.
Toast.makeText(baseContext, "Authentication failed.",
Toast.LENGTH_SHORT).show()
}
}
.addOnFailureListener{
Toast.makeText(this, "error occurred ${it.localizedMessage}", Toast.LENGTH_SHORT)
.show()
}
}
}
}
activity_login.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
android:background="@color/purple_700"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/signin"
android:text="Sign in"
android:textColor="@color/white"
android:textSize="35dp"
android:textStyle="bold"
android:layout_margin="50dp"
android:gravity="center"/>
<EditText
android:id="@+id/username"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/signin"
android:layout_marginStart="30dp"
android:layout_marginTop="10dp"
android:layout_marginEnd="30dp"
android:layout_marginBottom="30dp"
android:background="#30ffffff"
android:drawableLeft="@drawable/baseline_account_circle_24"
android:drawablePadding="20dp"
android:hint="Email"
android:padding="20dp"
android:textColor="@color/white"
android:textColorHint="@color/white" />
<EditText
android:id="@+id/passwordd"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/username"
android:layout_marginStart="30dp"
android:layout_marginTop="10dp"
android:layout_marginEnd="30dp"
android:layout_marginBottom="30dp"
android:background="#30ffffff"
android:drawableLeft="@drawable/baseline_password_24"
android:drawablePadding="20dp"
android:hint="Password"
android:inputType="textPassword"
android:padding="20dp"
android:textColor="@color/white"
android:textColorHint="@color/white" />
<com.google.android.material.button.MaterialButton
android:id="@+id/loginbtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/passwordd"
android:layout_centerHorizontal="true"
android:layout_marginStart="20dp"
android:layout_marginTop="20dp"
android:layout_marginEnd="20dp"
android:layout_marginBottom="20dp"
android:backgroundTint="@color/design_default_color_secondary"
android:text="LOGIN" />
<TextView
android:id="@+id/forgotpass"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/loginbtn"
android:layout_centerHorizontal="true"
android:layout_marginStart="20dp"
android:layout_marginTop="0dp"
android:layout_marginEnd="20dp"
android:layout_marginBottom="20dp"
android:text="Forgot password?"
android:textColor="@color/white" />
<com.google.android.material.button.MaterialButton
android:id="@+id/rgbtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/forgotpass"
android:layout_centerHorizontal="true"
android:layout_marginStart="20dp"
android:layout_marginTop="50dp"
android:layout_marginEnd="20dp"
android:layout_marginBottom="20dp"
android:textColor="@color/white"
android:background="@android:color/transparent"
android:text="dont have an account? sign up now" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/others"
android:layout_above="@id/socialicons"
android:text="or sign in with"
android:textColor="@color/white"
android:layout_centerHorizontal="true"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/socialicons"
android:layout_alignParentBottom="true"
android:gravity="center">
<ImageView
android:layout_width="48dp"
android:layout_height="48dp"
android:layout_margin="20dp"
android:src="@drawable/google"/>
<ImageView
android:layout_width="48dp"
android:layout_height="48dp"
android:layout_margin="20dp"
android:src="@drawable/facebook"/>
<ImageView
android:layout_width="48dp"
android:layout_height="48dp"
android:layout_margin="20dp"
android:src="@drawable/twitter"/>
</LinearLayout>
</RelativeLayout>
activity_main.xml
<?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"
android:background="@color/white"
tools:context=".RegisterActivity">
<TextView
android:id="@+id/name21"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="120dp"
android:text="Loading..."
android:gravity="center"
android:textSize="20dp"
android:textStyle="bold"
android:textColor="@color/black"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.459"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
</TextView>
<Button
android:id="@+id/logout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="284dp"
android:text="Logout"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent">
</Button>
</androidx.constraintlayout.widget.ConstraintLayout>
activity_register.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
android:background="@color/purple_700"
tools:context=".MainActivity">
<TextView
android:id="@+id/signuptitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="20dp"
android:layout_marginTop="20dp"
android:layout_marginEnd="20dp"
android:layout_marginBottom="20dp"
android:gravity="center"
android:text="Sign up"
android:textColor="@color/white"
android:textSize="35dp"
android:textStyle="bold" />
<EditText
android:id="@+id/phone"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/name"
android:layout_alignParentEnd="true"
android:layout_centerHorizontal="true"
android:layout_marginStart="10dp"
android:layout_marginTop="10dp"
android:layout_marginEnd="2dp"
android:layout_marginBottom="10dp"
android:inputType="phone"
android:background="#30ffffff"
android:drawableLeft="@drawable/baseline_local_phone_24"
android:drawablePadding="20dp"
android:hint="Phone Number"
android:padding="20dp"
android:textColor="@color/white"
android:textColorHint="@color/white" />
<EditText
android:id="@+id/name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/signuptitle"
android:layout_centerHorizontal="true"
android:layout_marginStart="10dp"
android:layout_marginTop="25dp"
android:layout_marginEnd="10dp"
android:layout_marginBottom="10dp"
android:background="#30ffffff"
android:drawableLeft="@drawable/baseline_account_circle_24"
android:drawablePadding="20dp"
android:hint="Name"
android:padding="20dp"
android:textColor="@color/white"
android:textColorHint="@color/white" />
<EditText
android:id="@+id/email"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/phone"
android:layout_marginStart="10dp"
android:layout_marginTop="10dp"
android:layout_marginEnd="10dp"
android:layout_marginBottom="10dp"
android:background="#30ffffff"
android:drawableLeft="@drawable/baseline_email_24"
android:drawablePadding="20dp"
android:hint="Email"
android:padding="20dp"
android:textColor="@color/white"
android:textColorHint="@color/white" />
<EditText
android:id="@+id/password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/email"
android:layout_marginStart="10dp"
android:layout_marginTop="10dp"
android:layout_marginEnd="10dp"
android:layout_marginBottom="10dp"
android:background="#30ffffff"
android:drawableLeft="@drawable/baseline_password_24"
android:drawablePadding="20dp"
android:hint="Password"
android:inputType="textPassword"
android:padding="20dp"
android:textColor="@color/white"
android:textColorHint="@color/white" />
<com.google.android.material.button.MaterialButton
android:id="@+id/signupbtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/password"
android:layout_alignParentStart="true"
android:layout_centerHorizontal="true"
android:layout_marginStart="151dp"
android:layout_marginTop="60dp"
android:backgroundTint="@color/design_default_color_secondary"
android:text="REGISTER"
android:textSize="15dp" />
<com.google.android.material.button.MaterialButton
android:id="@+id/lgbtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/signupbtn"
android:layout_centerHorizontal="true"
android:layout_marginTop="38dp"
android:text="Already have an account?"
android:textColor="@color/white"
android:background="@android:color/transparent"
android:textSize="15dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/info"
android:layout_above="@id/socialicons"
android:text="or sign up with"
android:textColor="@color/white"
android:layout_centerHorizontal="true"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/socialicons"
android:gravity="center"
android:layout_alignParentBottom="true">
<ImageView
android:layout_width="48dp"
android:layout_height="48dp"
android:layout_margin="20dp"
android:src="@drawable/google"/>
<ImageView
android:layout_width="48dp"
android:layout_height="48dp"
android:layout_margin="20dp"
android:src="@drawable/facebook"/>
<ImageView
android:layout_width="48dp"
android:layout_height="48dp"
android:layout_margin="20dp"
android:src="@drawable/twitter"/>
</LinearLayout>
</RelativeLayout>
And done. Now run your app.