Firebase Tutorial 2: Login in Android Application using Email and Password

Firebase is the a powerful platform for building iOS, Android, and web-based apps, offering real-time data storage and synchronization, user authentication, and more.

In this tutorials, we can learn how to login android application using firebase cloud platform. After develop the application, first we have to know how to configure android application in firebase, which is the basic thing of any android application start using fire. please read the above link.


To add Firebase to your app you'll need a Firebase project and a Firebase configuration file for your app.

  1. Create a Firebase project in the Firebase console, if you don't already have one. If you already have an existing Google project associated with your mobile app, click Import Google Project. Otherwise, click Create New Project.
  2. Click Add Firebase to your Android app and follow the setup steps. If you're importing an existing Google project, this may happen automatically and you can just download the config file.
  3. When prompted, enter your app's package name. It's important to enter the package name your app is using; this can only be set when you add an app to your Firebase project.
  4. At the end, you'll download a google-services.json file. You can download this file again at any time.
  5. If you haven't done so already, copy this into your project's module folder, typically app/.
Then, in your module Gradle file (usually the app/build.gradle), add the authentication library in dependencies section.

com.google.firebase:firebase-auth:9.8.0

Now, In firebase, we know, there are many way to gives the user authentication like email/password, google, facebook, twitter, github and anonymous.

Lets start how to sign in using email/password.

After setting all the dependencies, you have to go project and left side there is Authentication section and go to sign-in method and enable the email/password section. Default it is disable, if you don't set the enable it won't work.


Now go to LoginActivity.java file,

Declare the FirebaseAuth and AuthStateListener objects. 

private FirebaseAuth mAuth; 
private FirebaseAuth.AuthStateListener mAuthListener;

In the onCreate() method, initialize the FirebaseAuth instance and the AuthStateListener method so you can track whenever the user signs in or out. 

mAuth = FirebaseAuth.getInstance();
firebaseAuthListener= new FirebaseAuth.AuthStateListener() {
            @Override
            public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {

                FirebaseUser firebaseUser=firebaseAuth.getCurrentUser();
                if(firebaseUser!=null){
                    Log.e(TAG," onAuthStateChange: singed_in"+firebaseUser.getUid());
                }else{
                    Log.e(TAG," onAuthStateChange: singed_out");
                }
                updateUI(firebaseUser);
            }
        };

Attach the listener to your FirebaseAuth instance in the onStart() method and remove it on onStop(). 

@Override
    protected void onStart() {
        super.onStart();
        mAuth.addAuthStateListener(firebaseAuthListener);
    }

    @Override
    protected void onStop() {
        super.onStop();
        if(mAuth!=null){
            mAuth.addAuthStateListener(firebaseAuthListener);
        }
    }

For creating new user, we have to get the email and password from edittext and validates them and create new user with the createUserWithEmailAndPassword method.

// create new account
    public void createNewAccount(String email, String password){
        if(!validateForm()){
            return;
        }

        showProgressDialog();

        mAuth.createUserWithEmailAndPassword(email,password)
                .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {

                         if(!task.isSuccessful()){
                             Toast.makeText(LoginActivity.this,"User Create Sucessuflly", Toast.LENGTH_SHORT).show();
                         }
                        hideProgressDialog();
                    }
                });


    }

For sign in existing user,  get the email and password from edittext field and validates them and signs a user in with the signInWithEmailAndPassword method.

// sign in exising user
public  void singIn(String email, String password){
        if(!validateForm()){
            return;
        }

        showProgressDialog();
        mAuth.signInWithEmailAndPassword(email, password)
                .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {

                        if(!task.isSuccessful()){
                            Toast.makeText(LoginActivity.this,"User Login Failed", Toast.LENGTH_SHORT).show();
                            tvStatus.setText("Authentication Failed, Create New Account or Enter correct Credentials");
                        }

                        hideProgressDialog();
                    }
                });

    }

Yes, there is featues in firebase we can access the information about the signedIn user and there is a method getCurrentUser.

//geting user information
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user != null) {
    // Name, email address.
    String name = user.getDisplayName();
  String email = user.getEmail();
}


Hope you will understand how to login using email/password. 

Please if you want more information about go to firebase doc.


Happy Coding !!!

Firebase Tutorial: 1. How to start firebase in android studio

Firebase is a mobile platform that helps you quickly develop high-quality apps, grow your user base, and earn more money. Firebase is made up of complementary features that you can mix-and-match to fit your needs.

Implementing Firebase is quick and easy. With spontaneous APIs packaged into a single SDK, you can focus on solving your customers' problems and not waste time building complex infrastructure.
Most Firebase features are free forever, for any scale. Firebase also handles large number hit and scaling server capacity.


Steps that you have to do integrate firebase in Android:Step 1. 
Go to https://console.firebase.google.com/   and Click on Create New Project.


Step 2.

Give the name of Project in project name field and select the country/region and click the button Create Project.

Step 3.

Then you will see the overview page, and this page you will choose Add firebase to your Android app.


Step 4.
Now, you will see the screen, where you put the  package name of android project, just copy from the androidmanifest.xml. and there optional section App nickname , you can put any nickname of your application. Next one is Debug signing certificate SHA-1  is also optional. and Click Add Project.



Step 5.

After Click Add project, google-services.json fill will automatically downloaded in you device. and Switch to the Project view in Android Studio to see your project root directory.
Move the google-services.json file you just downloaded into your Android app module root directory and click continue.

Step 6. 
Now, you have to add dependencies. Google services plugin for Gradle loads the google-services.json file you just downloaded. Modify your build.gradle files to use the plugin after adding all the dependencies click finish.
  1. Project-level build.gradle (<project>/build.gradle):
    buildscript {
      dependencies {
        // Add this line
        classpath 'com.google.gms:google-services:3.0.0'
      }
    }
  2. App-level build.gradle (<project>/<app-module>/build.gradle):
    ...
    // Add to the bottom of the file
    apply plugin: 'com.google.gms.google-services'
    includes Firebase Analytics by default help_outline
  3. Finally, press "Sync now" in the bar that appears in the IDE:


Step 8.
Your firebase project is ready to use.You can use as your requirement.


Before start any android application, here is the some libraries are available for the various Firebase features(https://firebase.google.com/docs/android/setup) , you have to add on app/build.gradle.

Gradle Dependency Line Service
com.google.firebase:firebase-core:9.6.1 Analytics
com.google.firebase:firebase-database:9.6.1 Realtime Database
com.google.firebase:firebase-storage:9.6.1 Storage
com.google.firebase:firebase-crash:9.6.1 Crash Reporting
com.google.firebase:firebase-auth:9.6.1 Authentication
com.google.firebase:firebase-messaging:9.6.1 Cloud Messaging and Notifications
com.google.firebase:firebase-config:9.6.1 Remote Config
com.google.firebase:firebase-invites:9.6.1 Invites and Dynamic Links
com.google.firebase:firebase-ads:9.6.1 AdMob
com.google.android.gms:play-services-appindexing:9.6.1 App Indexing

If you want to know more about firebase, Here is the useful video links
Firebase sample: https://firebase.google.com/docs/samples/
Firebase on Android - Tutorials: https://www.youtube.com/playlist?list=PLl-K7zZEsYLmxfvI4Ds2Atko79iVvxlaq
Getting started with Firebase and Android - Firecasts #1
Retrieving data in realtime with Firebase Events - Firecasts #2
Realtime RecyclerViews with FirebaseUI - Firecasts #3
Getting started with Firebase and Angular - Firecasts #4

Happy Coding !!!