DEV Community

Harsh Lade
Harsh Lade

Posted on • Edited on

Authentication in Android Project with Firebase.

Introduction

We discussed the benefits and implementation of Firebase in our Android Studio Project. In this article, we will see the practical use of Firebase, we will learn how to use Authentication for your app using Firebase.

Prerequisites

  • Firebase has already been integrated in project.
  • google-service.json file has been added in your project.

Implementation

###1. Add Firebase authentication dependency in your build.gradle:

dependencies{
    //other dependencies...
    implementaion("com.google.firebase:firebase-auth:22.1.0")
}
Enter fullscreen mode Exit fullscreen mode

2. Initialize authentication in your App.

Add a Firebase instance in your project.

    private val firebaseInstance=FirebaseAuth.getInstance()
Enter fullscreen mode Exit fullscreen mode

3. Add Functionalities to Your App.

  • Sign In Functionality.
 fun signIn(email:String, password: String, context: Context) {
        firebaseInstance
            .signInWithEmailAndPassword(email, password)
            .addOnCompleteListener { task->
                if(task.isSuccessful) {
                    val user = firebaseInstance.currentUser?.email
                    Toast.makeText(context, "Sign in successful- $user", Toast.LENGTH_SHORT).show()
                }
                else{
                    Toast.makeText(context, "Failed, error: ${task.exception?.message}", Toast.LENGTH_SHORT).show()
                }
            }
    }
Enter fullscreen mode Exit fullscreen mode
  • Sign Up functionality.
 fun signUp(email:String, password: String, context: Context){
        firebaseInstance.createUserWithEmailAndPassword(email,password)
            .addOnCompleteListener { task->
                if(task.isSuccessful) {
                    val user = firebaseInstance.currentUser?.email
                    Toast.makeText(context, "Sign-up successful- $user", Toast.LENGTH_SHORT).show()
                }
                else{
                    Toast.makeText(context, "Failed, error: ${task.exception?.message}", Toast.LENGTH_SHORT).show()
                }
            }
    }
Enter fullscreen mode Exit fullscreen mode
  • Sign Out Functioality.
fun signOut(context: Context){
        firebaseInstance.signOut()
        Toast.makeText(context, "User signed out.", Toast.LENGTH_SHORT).show()
    }
Enter fullscreen mode Exit fullscreen mode
  • Manage User Session.
fun checkUserSession() {
    val user = firebaseAuth.currentUser
    if (user != null) {
        println("User already signed in: ${user.email}")
    } else {
        println("No user signed in.")
    }
}
Enter fullscreen mode Exit fullscreen mode

Conclusion.

We have discussed the application of Firebase. We will learn more about Firebase in upcoming lecture, so stay tuned.

Top comments (0)