Bird
Raised Fist0
Android Kotlinmobile~20 mins

Firebase Authentication in Android Kotlin - Mini App: Build & Ship

Choose your learning style10 modes available
Build: Login Screen
This screen allows users to sign in using their email and password with Firebase Authentication.
Target UI
-------------------------
|       Login Screen     |
|-----------------------|
| Email: [___________]  |
| Password: [_______]   |
|                       |
| [Login Button]         |
|                       |
| Don't have an account?|
| [Register Button]      |
-------------------------
Two EditText fields for email and password input.
A Login button that authenticates the user with Firebase.
A Register button that navigates to a registration screen (navigation can be a placeholder).
Show a Toast message on successful login or failure.
Disable the Login button while authentication is in progress.
Starter Code
Android Kotlin
package com.example.firebaseauth

import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.google.firebase.auth.FirebaseAuth

class LoginActivity : AppCompatActivity() {
    private lateinit var auth: FirebaseAuth
    private lateinit var emailEditText: EditText
    private lateinit var passwordEditText: EditText
    private lateinit var loginButton: Button
    private lateinit var registerButton: Button

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

        auth = FirebaseAuth.getInstance()

        emailEditText = findViewById(R.id.emailEditText)
        passwordEditText = findViewById(R.id.passwordEditText)
        loginButton = findViewById(R.id.loginButton)
        registerButton = findViewById(R.id.registerButton)

        // TODO: Implement loginButton click listener
        // TODO: Implement registerButton click listener
    }
}
Task 1
Task 2
Task 3
Task 4
Solution
Android Kotlin
package com.example.firebaseauth

import android.content.Intent
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.google.firebase.auth.FirebaseAuth

class LoginActivity : AppCompatActivity() {
    private lateinit var auth: FirebaseAuth
    private lateinit var emailEditText: EditText
    private lateinit var passwordEditText: EditText
    private lateinit var loginButton: Button
    private lateinit var registerButton: Button

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

        auth = FirebaseAuth.getInstance()

        emailEditText = findViewById(R.id.emailEditText)
        passwordEditText = findViewById(R.id.passwordEditText)
        loginButton = findViewById(R.id.loginButton)
        registerButton = findViewById(R.id.registerButton)

        loginButton.setOnClickListener {
            val email = emailEditText.text.toString().trim()
            val password = passwordEditText.text.toString().trim()

            if (email.isEmpty() || password.isEmpty()) {
                Toast.makeText(this, "Please enter email and password", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }

            loginButton.isEnabled = false

            auth.signInWithEmailAndPassword(email, password)
                .addOnCompleteListener(this) { task ->
                    loginButton.isEnabled = true
                    if (task.isSuccessful) {
                        Toast.makeText(this, "Login successful", Toast.LENGTH_SHORT).show()
                        // TODO: Navigate to main app screen
                    } else {
                        Toast.makeText(this, "Authentication failed: ${task.exception?.message}", Toast.LENGTH_LONG).show()
                    }
                }
        }

        registerButton.setOnClickListener {
            Toast.makeText(this, "Navigate to Register Screen", Toast.LENGTH_SHORT).show()
            // TODO: Implement navigation to RegisterActivity
        }
    }
}

This solution uses FirebaseAuth to sign in users with email and password. We get the input from EditText fields and check if they are not empty. When the login button is clicked, it disables itself to prevent multiple clicks during the authentication process. After Firebase responds, it re-enables the button. On success, it shows a Toast message and you can add navigation to the main app screen. On failure, it shows the error message. The register button currently shows a Toast as a placeholder for navigation to a registration screen.

Final Result
Completed Screen
-------------------------
|       Login Screen     |
|-----------------------|
| Email: [user@example] |
| Password: [•••••••]   |
|                       |
| [Login Button]         |
|                       |
| Don't have an account?|
| [Register Button]      |
-------------------------
User enters email and password.
Taps Login button: button disables, Firebase authenticates.
On success: Toast 'Login successful' appears.
On failure: Toast with error message appears.
Taps Register button: Toast 'Navigate to Register Screen' appears.
Stretch Goal
Add a progress indicator (spinner) that shows while the login is in progress.
💡 Hint
Use a ProgressBar view and toggle its visibility when login starts and ends.

Practice

(1/5)
1. What is the main purpose of Firebase Authentication in an Android app?
easy
A. To store user data in a database
B. To send push notifications to users
C. To design the app's user interface
D. To securely manage user sign-in and registration

Solution

  1. Step 1: Understand Firebase Authentication role

    Firebase Authentication is designed to handle user sign-in and registration securely.
  2. Step 2: Differentiate from other Firebase services

    It does not store user data (that's Firestore/Realtime Database), nor handle UI design or notifications.
  3. Final Answer:

    To securely manage user sign-in and registration -> Option D
  4. Quick Check:

    Firebase Authentication = Secure sign-in [OK]
Hint: Remember Firebase Auth is for user sign-in only [OK]
Common Mistakes:
  • Confusing Authentication with database storage
  • Thinking it handles UI design
  • Assuming it manages notifications
2. Which Kotlin code snippet correctly registers a new user with email and password using Firebase Authentication?
easy
A. firebaseAuth.registerUser(email, password).addOnCompleteListener { ... }
B. firebaseAuth.signInWithEmailAndPassword(email, password).addOnCompleteListener { ... }
C. firebaseAuth.createUserWithEmailAndPassword(email, password).addOnCompleteListener { ... }
D. firebaseAuth.createUser(email, password).addOnCompleteListener { ... }

Solution

  1. Step 1: Identify correct Firebase method for registration

    The method to register a new user is createUserWithEmailAndPassword(email, password).
  2. Step 2: Check method names in options

    registerUser and createUser do not exist. signInWithEmailAndPassword is for signing in existing users, not registration.
  3. Final Answer:

    firebaseAuth.createUserWithEmailAndPassword(email, password).addOnCompleteListener { ... } -> Option C
  4. Quick Check:

    Register new user = createUserWithEmailAndPassword [OK]
Hint: Register uses createUserWithEmailAndPassword method [OK]
Common Mistakes:
  • Using signInWithEmailAndPassword to register
  • Using non-existent methods like createUser or registerUser
  • Confusing method names
3. Given this Kotlin code snippet, what will be printed if the user is signed in?
val user = firebaseAuth.currentUser
if (user != null) {
    println("User is signed in")
} else {
    println("No user signed in")
}
medium
A. User is signed in
B. NullPointerException error
C. No user signed in
D. Compilation error

Solution

  1. Step 1: Understand currentUser property

    firebaseAuth.currentUser returns the current signed-in user or null if none.
  2. Step 2: Analyze the if condition

    If user is not null, it prints "User is signed in"; otherwise, "No user signed in".
  3. Final Answer:

    User is signed in -> Option A
  4. Quick Check:

    currentUser != null means user signed in [OK]
Hint: currentUser null means no user; else signed in [OK]
Common Mistakes:
  • Assuming currentUser throws error if null
  • Confusing sign-in check logic
  • Expecting compilation errors incorrectly
4. Identify the error in this Kotlin code for signing out a user:
firebaseAuth.signOut
println("User signed out")
medium
A. signOut is not a FirebaseAuth method
B. Missing parentheses after signOut method
C. println should be inside a callback
D. No error, code is correct

Solution

  1. Step 1: Check signOut method usage

    signOut is a method and requires parentheses: signOut()
  2. Step 2: Verify other options

    signOut exists in FirebaseAuth; println can be outside callback; so only missing parentheses is error.
  3. Final Answer:

    Missing parentheses after signOut method -> Option B
  4. Quick Check:

    signOut() needs parentheses [OK]
Hint: Methods need () even if no parameters [OK]
Common Mistakes:
  • Forgetting parentheses on method calls
  • Thinking signOut is a property
  • Assuming println must be in callback
5. You want to create a function in Kotlin that registers a user and then immediately signs them in using Firebase Authentication. Which code snippet correctly does this?
hard
A. firebaseAuth.createUserWithEmailAndPassword(email, password).addOnCompleteListener { task -> if (task.isSuccessful) { println("User registered and signed in") } }
B. firebaseAuth.signInWithEmailAndPassword(email, password).addOnCompleteListener { task -> if (task.isSuccessful) { println("User registered and signed in") } }
C. firebaseAuth.createUserWithEmailAndPassword(email, password).addOnCompleteListener { task -> if (task.isSuccessful) { firebaseAuth.signInWithEmailAndPassword(email, password) } }
D. firebaseAuth.createUserWithEmailAndPassword(email, password).addOnCompleteListener { task -> if (task.isSuccessful) { firebaseAuth.signOut() } }

Solution

  1. Step 1: Understand createUserWithEmailAndPassword behavior

    This method registers and automatically signs in the user if successful.
  2. Step 2: Analyze options for correct flow

    createUserWithEmailAndPassword(...).addOnCompleteListener { task -> if (task.isSuccessful) { println("User registered and signed in") } } registers and confirms success. signInWithEmailAndPassword only signs in existing users. Calling signIn after createUser is redundant. Calling signOut after is incorrect.
  3. Final Answer:

    firebaseAuth.createUserWithEmailAndPassword(email, password).addOnCompleteListener { task -> if (task.isSuccessful) { println("User registered and signed in") } } -> Option A
  4. Quick Check:

    Registration auto signs in [OK]
Hint: Register auto signs in; no need to call signIn after [OK]
Common Mistakes:
  • Calling signIn after createUserWithEmailAndPassword unnecessarily
  • Using signIn without registering first
  • Signing out immediately after registration
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard