Open In App

User authentication using Firebase in Android

Last Updated : 01 Jul, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Firebase is a mobile and web application development platform. It provides services that a web application or mobile application might require. Firebase provides email and password authentication without any overhead of building backend for user authentication.

Steps for firebase user authentication are:

  • Step 1:
    Create a new project on android studio or open an existing project in which you want to add authentication and add the firebase to that android application.Steps to add firebase are very well explained in following link : https://www.geeksforgeeks.org/adding-firebase-to-android-app/

  • Step 2:
    Go to Firebase console (http://console.firebase.google.com/) navigate to your application, and under the authentication tab, enable email/pass authentication.

  • Step 3: activity_registration.xml
    This is your sign-up activity. It has two EditTexts, a TextView, a Button and a Progress Bar. All these views are contained in a Linear Layout with vertical orientation. EditTexts are used to get email and password from the user. Button is used for signup purpose after filling username and password.
    Complete xml code for registration activity(activity_registration) is:

    activity_registration.xml




    <?xml version="1.0" encoding="utf-8"?>
      
    <!-- Linear Layout with vertical orientation and other properties -->
    <LinearLayout
        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:gravity="center_vertical"
        android:orientation="vertical"
        android:padding="15dp"
        tools:context=".RegistrationActivity">
      
        <!-- TextView for heading -->
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Register" />
      
        <!-- Edit text for email -->
        <EditText
            android:id="@+id/email"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Enter your Email" />
      
        <!-- Edit text for password -->
        <EditText
            android:id="@+id/passwd"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Enter your Password"
            android:inputType="textPassword" />
      
        <!-- Button for register with text "Register" -->
        <Button
            android:id="@+id/btnregister"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Register" />
      
        <!-- ProgressBar for loading time -->
        <ProgressBar
            android:id="@+id/progressbar"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:visibility="gone" />
    </LinearLayout>

    
    

  • Step 4: RegistrationActivity.java
    • Now turn is of Java code for registration activity.
    • In this, we have a one-click listener attached to the button. On button click, registerNewUser() is called.In this method, it is checked if any of the parameters that are email and password is not empty. If that’s the case then an error message is displayed. If both Edit texts have data, then createUserWithEmailAndPassword() method is invoked.
    • To register a new user createUserWithEmailAndPassword() function is used which intakes two-parameter that is email and password for which you want to register.Inside createUserWithEmailAndPassword() method, task success is checked. If the task is successful then the user is directed to MainActivity or dashboard else a Toast message with “registration failed” is displayed.
    • For user authentication we have to take reference to the FirebaseAuth.We can take reference using getInstance function.Code snippet is:
      FirebaseAuth mAuth = FirebaseAuth.getInstance();

    Java code for registration activity is:

    RegistrationActivity.java




    package com.geeksforgeeks.firebaseuserauthentication;
      
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.content.Intent;
    import android.view.View;
    import android.widget.Toast;
    import android.widget.EditText;
    import android.widget.TextView;
    import android.widget.Button;
      
    import com.google.firebase.auth.FirebaseAuth;
    import com.google.firebase.auth.AuthResult;
    import com.google.android.gms.tasks.OnCompleteListener;
    import com.google.android.gms.tasks.Task;
      
    public class RegistrationActivity extends AppCompatActivity {
      
        private EditText emailTextView, passwordTextView;
        private Button Btn;
        private ProgressBar progressbar;
        private FirebaseAuth mAuth;
      
        @Override
        protected void onCreate(Bundle savedInstanceState)
        {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_registration);
      
            // taking FirebaseAuth instance
            mAuth = FirebaseAuth.getInstance();
      
            // initialising all views through id defined above
            emailTextView = findViewById(R.id.email);
            passwordTextView = findViewById(R.id.passwd);
            Btn = findViewById(R.id.btnregister);
            progressbar = findViewById(R.id.progressbar);
      
            // Set on Click Listener on Registration button
            Btn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v)
                {
                    registerNewUser();
                }
            });
        }
      
        private void registerNewUser()
        {
      
            // show the visibility of progress bar to show loading
            progressbar.setVisibility(View.VISIBLE);
      
            // Take the value of two edit texts in Strings
            String email, password;
            email = emailTextView.getText().toString();
            password = passwordTextView.getText().toString();
      
            // Validations for input email and password
            if (TextUtils.isEmpty(email)) {
                Toast.makeText(getApplicationContext(),
                               "Please enter email!!",
                               Toast.LENGTH_LONG)
                    .show();
                return;
            }
            if (TextUtils.isEmpty(password)) {
                Toast.makeText(getApplicationContext(),
                               "Please enter password!!",
                               Toast.LENGTH_LONG)
                    .show();
                return;
            }
      
            // create new user or register new user
            mAuth
                .createUserWithEmailAndPassword(email, password)
                .addOnCompleteListener(new OnCompleteListener<AuthResult>() {
      
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task)
                    {
                        if (task.isSuccessful()) {
                            Toast.makeText(getApplicationContext(),
                                           "Registration successful!",
                                           Toast.LENGTH_LONG)
                                .show();
      
                            // hide the progress bar
                            progressBar.setVisibility(View.GONE);
      
                            // if the user created intent to login activity
                            Intent intent
                                = new Intent(RegistrationActivity.this,
                                             MainActivity.class);
                            startActivity(intent);
                        }
                        else {
      
                            // Registration failed
                            Toast.makeText(
                                     getApplicationContext(),
                                     "Registration failed!!"
                                         + " Please try again later",
                                     Toast.LENGTH_LONG)
                                .show();
      
                            // hide the progress bar
                            progressBar.setVisibility(View.GONE);
                        }
                    }
                });
        }
    }

    
    

  • Step 5: activity_login.xml
    Now after registration activity we have to create login activity.Layout of login activity is similar to signup activity with two Edit texts, one button, a Text View for heading all contained in Linear Layout with vertical orientation.Here is complete code for xml file of activity_login.xml:

    activity_login.xml




    <?xml version="1.0" encoding="utf-8"?>
    <!-- Linear Layout with vertical orientation and other properties -->
      
    <LinearLayout
        xmlns:tools="http://schemas.android.com/tools"
          
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center_vertical"
        android:orientation="vertical"
        android:padding="15dp"
        tools:context=".LoginActivity">
          
        <!-- TextView for heading -->
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Login"/>
              
        <!-- Edit text for email -->
        <EditText
            android:id="@+id/email"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Enter your Email" />
              
        <!-- Edit text for password -->
        <EditText
            android:id="@+id/password"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Enter your Password"
            android:inputType="textPassword" />
              
        <!-- Button for Login with text "Login" -->
        <Button
            android:id="@+id/login"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Login" />
              
        <!-- ProgressBar for Loading Time -->
        <ProgressBar
            android:id="@+id/progressBar"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:visibility="gone" />
    </LinearLayout>

    
    

  • Step 6: LoginActivity.java
    Here code is very much similar to RegistrationActivity but for signin signInWithEmailAndPassword() function is used which takes email and password as parameter and if that user with email and password exists then you will be redirected to mainactivity or Dashboard.Inside signInWithEmailAndPassword() method, task success is checked. If task is successful then user is directed to Mainactivity or dashboard else a Toast message with “Login failed” is displayed.Java code for login activity is:

    LoginActivity.java




    package com.geeksforgeeks.firebaseuserauthentication;
      
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.content.Intent;
    import android.view.View;
    import android.widget.Toast;
    import android.widget.EditText;
    import android.widget.TextView;
    import android.widget.Button;
      
    import com.google.firebase.auth.FirebaseAuth;
    import com.google.firebase.auth.AuthResult;
    import com.google.android.gms.tasks.OnCompleteListener;
    import com.google.android.gms.tasks.Task;
      
    public class LoginActivity extends AppCompatActivity {
      
        private EditText emailTextView, passwordTextView;
        private Button Btn;
        private ProgressBar progressbar;
      
        private FirebaseAuth mAuth;
        @Override
        protected void onCreate(Bundle savedInstanceState)
        {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_login);
            // taking instance of FirebaseAuth
            mAuth = FirebaseAuth.getInstance();
      
            // initialising all views through id defined above
            emailTextView = findViewById(R.id.email);
            passwordTextView = findViewById(R.id.password);
            Btn = findViewById(R.id.login);
            progressbar = findViewById(R.id.progressBar);
      
            // Set on Click Listener on Sign-in button
            Btn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v)
                {
                    loginUserAccount();
                }
            });
        }
      
        private void loginUserAccount()
        {
      
            // show the visibility of progress bar to show loading
            progressbar.setVisibility(View.VISIBLE);
      
            // Take the value of two edit texts in Strings
            String email, password;
            email = emailTextView.getText().toString();
            password = passwordTextView.getText().toString();
      
            // validations for input email and password
            if (TextUtils.isEmpty(email)) {
                Toast.makeText(getApplicationContext(),
                               "Please enter email!!",
                               Toast.LENGTH_LONG)
                    .show();
                return;
            }
      
            if (TextUtils.isEmpty(password)) {
                Toast.makeText(getApplicationContext(),
                               "Please enter password!!",
                               Toast.LENGTH_LONG)
                    .show();
                return;
            }
      
            // signin existing user
            mAuth.signInWithEmailAndPassword(email, password)
                .addOnCompleteListener(
                    new OnCompleteListener<AuthResult>() {
                        @Override
                        public void onComplete(
                            @NonNull Task<AuthResult> task)
                        {
                            if (task.isSuccessful()) {
                                Toast.makeText(getApplicationContext(),
                                               "Login successful!!",
                                               Toast.LENGTH_LONG)
                                    .show();
      
                                // hide the progress bar
                                progressBar.setVisibility(View.GONE);
      
                                // if sign-in is successful
                                // intent to home activity
                                Intent intent
                                    = new Intent(LoginActivity.this,
                                                 MainActivity.class);
                                startActivity(intent);
                            }
      
                            else {
      
                                // sign-in failed
                                Toast.makeText(getApplicationContext(),
                                               "Login failed!!",
                                               Toast.LENGTH_LONG)
                                    .show();
      
                                // hide the progress bar
                                progressbar.setVisibility(View.GONE);
                            }
                        }
                    });
        }
    }

    
    

  • Step 7: activity_main.xml
    This is dashboard activity which contains simple text view in Relative layout.Code is as below:

    activity_main.xml




    <RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:gravity="center"
        tools:context=".MainActivity">
          
        <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="GeeksForGeeks(Firebase Authentication)"
                android:textSize="20dp"
               />
    </RelativeLayout>

    
    

  • Step 8: MainActivity.java
    MainActivity contains the code for dashboard to which user is redirected after login or registration.

    MainActivity.java




    package com.geeksforgeeks.firebaseuserauthentication;
      
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.content.Intent;
    import android.view.View;
    import android.widget.Toast;
    import android.widget.EditText;
    import android.widget.TextView;
    import android.widget.Button;
      
    public class MainActivity extends AppCompatActivity {
      
        private TextView geeksforgeeks;
      
        @Override
        protected void onCreate(Bundle savedInstanceState)
        {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_login);
      
            // initialising all views through id defined above
            geeksforgeeks = findViewById(R.id.gfg);
            geeksforgeeks.setText(
                "GeeksForGeeks(Firebase Authentication)");
        }
    }

    
    

Output:

  • Registering New user

    Register activity containing email and password field

  • Registration successful

    Main Activity when the Registration is successful

  • The new User data are stored on firebase successfully. You can see the registered users on the firebase console of the application after the Registration successful step.
    registered users

    registered users

  • User trying to login with the just registered credentials

    Login activity with email and password field



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads