With the latest news from Google I/O comes the new and upgraded Firebase. To demonstrate how simplified and easy to use firebase is, we will build a simple login / register (Firebase Authentication) demo using the Firebase Email & Password authentication.

Firebase provides a full set of authentication options out-of-the-box. Firebase automatically stores your users’ credentials securely (using bcrypt) and redundantly (with replication and daily off-site backups). This separates sensitive user credentials from your application data, and lets you focus on the user interface and experience for your app.

android-getting-started-with-firebase

Features of Firebase

Firebase comes with bunch features essential for every android app starting from authentication to hosting the app.

google firebase android features

Below are the advantages using Firebase in general:
> Super easy and quick to implement.
> No server side configuration needed. No PHP Scripts and No Database Designs.
> Realtime update without using GCM.
> Autoscaling built-in
> Can start for free (only need to start paying once we hit 50 connections)
> Robust APIs for Javascript (including several frameworks like Angular), iOS, and Android
> Built-in support for authentication services like Facebook, Google, and Twitter
> Declarative Security Rules model allows us to enforce read/write privileges and data validation throughout the tree

Some of the disadvantages of Firebase can be sum up in the following:
> Need to build indexes manually
> May need to build “event log” manually as well (in separate sub-tree?)
> Implementation of REST API could be difficult on embedded platforms
> Data validation rules do not support complex objects directly (you’d need to validate individual child nodes separately)

1. Enabling Firebase Auth

1. First thing you need to do is go to https://firebase.google.com/ and make an account to gain access to their console. After you gain access to the console you can start by creating your first project.

2. Give the package name of your project (mine is info.androidhive.firebase) in which you are going to integrate the Firebase. Here the google-services.json file will be downloaded when you press add app button.

3. Next go to your project dashboard. Find the Auth and click get started. Go to set up sign in method and choose Email & Password and enable it.

android-adding-firebase-to-your-project

Now we are ready to start with our Android project. We are going to create a simple app which contains firebase authentication and profile management. Overall we are going to see how to add Login, Registration, Forgot Password, Change Email, Change Password & finally Sign Out option.

2. Creating Android Project

1. Create a new project in Android Studio from File ⇒ New Project. When it prompts you to select the default activity, select Blank Activity and proceed.

While filling the project details, use the same package name which you gave in firebase console. In my case I am using same info.androidhive.firebase.

2. Open AndroidManifest.xml and add the INTERNET permission as we need to make network calls.

<uses-permission android:name="android.permission.INTERNET" />

3. Paste the google-services.json file to your project’s app folder. This step is very important as your project won’t build without this file.

4. Now open the build.gradle located in project’s home directory and add firebase dependency.

dependencies {
        classpath 'com.android.tools.build:gradle:2.1.2'
        classpath 'com.google.gms:google-services:3.0.0'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }

5. Open app/build.gradle and add firebase auth dependency. At the very bottom of the file, add apply plugin: ‘com.google.gms.google-services’

dependencies {
    compile "com.google.firebase:firebase-auth:9.0.2"
}

apply plugin: 'com.google.gms.google-services'

6. Add the below resources to dimens.xml, colors.xml and strings.xml. These resources doesn’t require for firebase, but for this article.

<resources>
    <!-- Default screen margins, per the Android Design guidelines. -->
    <dimen name="activity_horizontal_margin">16dp</dimen>
    <dimen name="activity_vertical_margin">16dp</dimen>
    <dimen name="fab_margin">16dp</dimen>
    <dimen name="logo_w_h">100dp</dimen>
</resources>

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorPrimary">#00bcd4</color>
    <color name="colorPrimaryDark">#0097a7</color>
    <color name="colorAccent">#f2fe71</color>

    <color name="bg_login">#26ae90</color>
    <color name="bg_register">#2e3237</color>
    <color name="bg_main">#428bca</color>
    <color name="white">#ffffff</color>
    <color name="input_login">#222222</color>
    <color name="input_login_hint">#999999</color>
    <color name="input_register">#888888</color>
    <color name="input_register_bg">#3b4148</color>
    <color name="input_register_hint">#5e6266</color>
    <color name="btn_login">#26ae90</color>
    <color name="btn_login_bg">#eceef1</color>
    <color name="lbl_name">#333333</color>
    <color name="btn_logut_bg">#ff6861</color>
</resources>
<resources>
    <string name="app_name">Firebase Auth</string>
    <string name="action_sign_in_short">Register</string>
    <string name="email">Email</string>
    <string name="minimum_password">Password too short, enter minimum 6 characters!</string>
    <string name="auth_failed">Authentication failed, check your email and password or sign up</string>
    <string name="change_email">Change Email</string>
    <string name="change_password">Change Password</string>
    <string name="send_password_reset_email">Send Password reset email</string>
    <string name="remove_user">Remove user</string>
    <string name="new_pass">New Password</string>
    <string name="title_activity_profile">Firebase</string>
    <string name="title_activity_login">Sign in</string>
    <string name="hint_email">Email</string>
    <string name="hint_password">Password</string>
    <string name="hint_name">Fullname</string>
    <string name="btn_login">LOGIN</string>
    <string name="btn_link_to_register">Not a member? Get registered in Firebase now!</string>
    <string name="btn_link_to_login">Already registered. Login Me!</string>
    <string name="title_activity_reset_password">ResetPasswordActivity</string>
    <string name="btn_forgot_password">Forgot your password?</string>
    <string name="btn_reset_password">Reset Password</string>
    <string name="btn_back"><![CDATA[<< Back]]></string>
    <string name="hint_new_email">New Email</string>
    <string name="btn_change">Change</string>
    <string name="btn_send">Send</string>
    <string name="btn_remove">Remove</string>
    <string name="btn_sign_out">Sign Out</string>
    <string name="lbl_forgot_password">Forgot password?</string>
    <string name="forgot_password_msg">We just need your registered Email Id to sent you password reset instructions.</string>
</resources>

Now we have the project ready with all the dependencies added. Let’s start by adding the sign up screen.

2.1 Sign Up with Email & Password

Sign up screen contains two EditText fields for email and password. And few buttons to navigate to login and forgot password screens.

7. Create an activity named SignupActivity.java and add the following code to the layout file activity_signup.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout 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:fitsSystemWindows="true"
    tools:context="info.androidhive.firebase.LoginActivity">

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:background="@color/colorPrimaryDark"
        android:gravity="center"
        android:orientation="vertical"
        android:padding="@dimen/activity_horizontal_margin">


        <ImageView
            android:layout_width="@dimen/logo_w_h"
            android:layout_height="@dimen/logo_w_h"
            android:layout_gravity="center_horizontal"
            android:layout_marginBottom="30dp"
            android:src="@mipmap/ic_launcher" />

        <android.support.design.widget.TextInputLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <EditText
                android:id="@+id/email"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="@string/email"
                android:inputType="textEmailAddress"
                android:maxLines="1"
                android:singleLine="true"
                android:textColor="@android:color/white" />

        </android.support.design.widget.TextInputLayout>

        <android.support.design.widget.TextInputLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <EditText
                android:id="@+id/password"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:focusableInTouchMode="true"
                android:hint="@string/hint_password"
                android:imeActionId="@+id/login"
                android:imeOptions="actionUnspecified"
                android:inputType="textPassword"
                android:maxLines="1"
                android:singleLine="true"
                android:textColor="@android:color/white" />

        </android.support.design.widget.TextInputLayout>

        <Button
            android:id="@+id/sign_up_button"
            style="?android:textAppearanceSmall"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="16dp"
            android:background="@color/colorAccent"
            android:text="@string/action_sign_in_short"
            android:textColor="@android:color/black"
            android:textStyle="bold" />

        <Button
            android:id="@+id/btn_reset_password"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="20dip"
            android:background="@null"
            android:text="@string/btn_forgot_password"
            android:textAllCaps="false"
            android:textColor="@color/colorAccent" />

        <!-- Link to Login Screen -->

        <Button
            android:id="@+id/sign_in_button"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="20dip"
            android:background="@null"
            android:text="@string/btn_link_to_login"
            android:textAllCaps="false"
            android:textColor="@color/white"
            android:textSize="15dp" />
    </LinearLayout>

    <ProgressBar
        android:id="@+id/progressBar"
        android:layout_width="30dp"
        android:layout_height="30dp"
        android:layout_gravity="center|bottom"
        android:layout_marginBottom="20dp"
        android:visibility="gone" />
</android.support.design.widget.CoordinatorLayout>

8. Open SignupActivity.java and add the following. Firebase provides createUserWithEmailAndPassword() method to create a new user with email and password data.

package info.androidhive.firebase;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;

public class SignupActivity extends AppCompatActivity {

    private EditText inputEmail, inputPassword;
    private Button btnSignIn, btnSignUp, btnResetPassword;
    private ProgressBar progressBar;
    private FirebaseAuth auth;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_signup);

        //Get Firebase auth instance
        auth = FirebaseAuth.getInstance();

        btnSignIn = (Button) findViewById(R.id.sign_in_button);
        btnSignUp = (Button) findViewById(R.id.sign_up_button);
        inputEmail = (EditText) findViewById(R.id.email);
        inputPassword = (EditText) findViewById(R.id.password);
        progressBar = (ProgressBar) findViewById(R.id.progressBar);
        btnResetPassword = (Button) findViewById(R.id.btn_reset_password);

        btnResetPassword.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(SignupActivity.this, ResetPasswordActivity.class));
            }
        });

        btnSignIn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        btnSignUp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                String email = inputEmail.getText().toString().trim();
                String password = inputPassword.getText().toString().trim();

                if (TextUtils.isEmpty(email)) {
                    Toast.makeText(getApplicationContext(), "Enter email address!", Toast.LENGTH_SHORT).show();
                    return;
                }

                if (TextUtils.isEmpty(password)) {
                    Toast.makeText(getApplicationContext(), "Enter password!", Toast.LENGTH_SHORT).show();
                    return;
                }

                if (password.length() < 6) {
                    Toast.makeText(getApplicationContext(), "Password too short, enter minimum 6 characters!", Toast.LENGTH_SHORT).show();
                    return;
                }

                progressBar.setVisibility(View.VISIBLE);
                //create user
                auth.createUserWithEmailAndPassword(email, password)
                        .addOnCompleteListener(SignupActivity.this, new OnCompleteListener<AuthResult>() {
                            @Override
                            public void onComplete(@NonNull Task<AuthResult> task) {
                                Toast.makeText(SignupActivity.this, "createUserWithEmail:onComplete:" + task.isSuccessful(), Toast.LENGTH_SHORT).show();
                                progressBar.setVisibility(View.GONE);
                                // If sign in fails, display a message to the user. If sign in succeeds
                                // the auth state listener will be notified and logic to handle the
                                // signed in user can be handled in the listener.
                                if (!task.isSuccessful()) {
                                    Toast.makeText(SignupActivity.this, "Authentication failed." + task.getException(),
                                            Toast.LENGTH_SHORT).show();
                                } else {
                                    startActivity(new Intent(SignupActivity.this, MainActivity.class));
                                    finish();
                                }
                            }
                        });

            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        progressBar.setVisibility(View.GONE);
    }
}

Open AndroidManifest.xml and make SignupActivity as launcher activity (temporarily) and test the sign up.

android-firebase-sign-up-screen

If you login to Firebase console, you can see the user created with the email id you have given the android app.

android-firebase-console-new-user

2.2 Log In with Email & Password

Now we’ll add the login screen and check the credentials we have created on sign up screen.

9. Create another activity named LoginActivity.java and add the below code to its layout file activity_login.xml.

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout 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:fitsSystemWindows="true"
    tools:context="info.androidhive.firebase.LoginActivity">

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:background="@color/colorPrimary"
        android:gravity="center"
        android:orientation="vertical"
        android:padding="@dimen/activity_horizontal_margin">


        <ImageView
            android:layout_width="@dimen/logo_w_h"
            android:layout_height="@dimen/logo_w_h"
            android:layout_gravity="center_horizontal"
            android:layout_marginBottom="30dp"
            android:src="@mipmap/ic_launcher" />

        <android.support.design.widget.TextInputLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <EditText
                android:id="@+id/email"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginBottom="10dp"
                android:hint="@string/hint_email"
                android:inputType="textEmailAddress"
                android:textColor="@android:color/white"
                android:textColorHint="@android:color/white" />
        </android.support.design.widget.TextInputLayout>

        <android.support.design.widget.TextInputLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <EditText
                android:id="@+id/password"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_marginBottom="10dp"
                android:hint="@string/hint_password"
                android:inputType="textPassword"
                android:textColor="@android:color/white"
                android:textColorHint="@android:color/white" />
        </android.support.design.widget.TextInputLayout>

        <!-- Login Button -->

        <Button
            android:id="@+id/btn_login"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="20dip"
            android:background="@color/colorAccent"
            android:text="@string/btn_login"
            android:textColor="@android:color/black" />

        <Button
            android:id="@+id/btn_reset_password"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="20dip"
            android:background="@null"
            android:text="@string/btn_forgot_password"
            android:textAllCaps="false"
            android:textColor="@color/colorAccent" />

        <!-- Link to Login Screen -->

        <Button
            android:id="@+id/btn_signup"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="20dip"
            android:background="@null"
            android:text="@string/btn_link_to_register"
            android:textAllCaps="false"
            android:textColor="@color/white"
            android:textSize="15dp" />
    </LinearLayout>

    <ProgressBar
        android:id="@+id/progressBar"
        android:layout_width="30dp"
        android:layout_height="30dp"
        android:layout_gravity="center|bottom"
        android:layout_marginBottom="20dp"
        android:visibility="gone" />
</android.support.design.widget.CoordinatorLayout>

10. Open LoginActivity.java and do the below changes. Firebase provides signInWithEmailAndPassword() method to sign in the user.

package info.androidhive.firebase;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;

public class LoginActivity extends AppCompatActivity {

    private EditText inputEmail, inputPassword;
    private FirebaseAuth auth;
    private ProgressBar progressBar;
    private Button btnSignup, btnLogin, btnReset;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //Get Firebase auth instance
        auth = FirebaseAuth.getInstance();

        if (auth.getCurrentUser() != null) {
            startActivity(new Intent(LoginActivity.this, MainActivity.class));
            finish();
        }

        // set the view now
        setContentView(R.layout.activity_login);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        inputEmail = (EditText) findViewById(R.id.email);
        inputPassword = (EditText) findViewById(R.id.password);
        progressBar = (ProgressBar) findViewById(R.id.progressBar);
        btnSignup = (Button) findViewById(R.id.btn_signup);
        btnLogin = (Button) findViewById(R.id.btn_login);
        btnReset = (Button) findViewById(R.id.btn_reset_password);

        //Get Firebase auth instance
        auth = FirebaseAuth.getInstance();

        btnSignup.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(LoginActivity.this, SignupActivity.class));
            }
        });

        btnReset.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(LoginActivity.this, ResetPasswordActivity.class));
            }
        });

        btnLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String email = inputEmail.getText().toString();
                final String password = inputPassword.getText().toString();

                if (TextUtils.isEmpty(email)) {
                    Toast.makeText(getApplicationContext(), "Enter email address!", Toast.LENGTH_SHORT).show();
                    return;
                }

                if (TextUtils.isEmpty(password)) {
                    Toast.makeText(getApplicationContext(), "Enter password!", Toast.LENGTH_SHORT).show();
                    return;
                }

                progressBar.setVisibility(View.VISIBLE);

                //authenticate user
                auth.signInWithEmailAndPassword(email, password)
                        .addOnCompleteListener(LoginActivity.this, new OnCompleteListener<AuthResult>() {
                            @Override
                            public void onComplete(@NonNull Task<AuthResult> task) {
                                // If sign in fails, display a message to the user. If sign in succeeds
                                // the auth state listener will be notified and logic to handle the
                                // signed in user can be handled in the listener.
                                progressBar.setVisibility(View.GONE);
                                if (!task.isSuccessful()) {
                                    // there was an error
                                    if (password.length() < 6) {
                                        inputPassword.setError(getString(R.string.minimum_password));
                                    } else {
                                        Toast.makeText(LoginActivity.this, getString(R.string.auth_failed), Toast.LENGTH_LONG).show();
                                    }
                                } else {
                                    Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                                    startActivity(intent);
                                    finish();
                                }
                            }
                        });
            }
        });
    }
}

11. Open AndroidManifest.xml and make the LoginActivity.java as launcher activity to make the login screen as first screen.

Run the project and login with the credentials which you used while signing up.

android-firebase-login-screen

2.3 Forgot Password – Send Reset Password Email

Another cool feature firebase provides is, sending reset password email when required. This is a very difficult task if you want to have your own email server.

12. Create another activity named ResetPasswordActivity.java and add the below code its layout file activity_reset_password.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout 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:layout_gravity="center"
    android:background="@color/colorPrimary"
    android:fitsSystemWindows="true"
    tools:context="info.androidhive.firebase.LoginActivity">

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="30dp"
        android:gravity="center"
        android:orientation="vertical"
        android:padding="@dimen/activity_horizontal_margin">


        <ImageView
            android:layout_width="@dimen/logo_w_h"
            android:layout_height="@dimen/logo_w_h"
            android:layout_gravity="center_horizontal"
            android:layout_marginBottom="10dp"
            android:src="@mipmap/ic_launcher" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:padding="10dp"
            android:text="@string/lbl_forgot_password"
            android:textColor="@android:color/white"
            android:textSize="20dp" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginBottom="10dp"
            android:gravity="center_horizontal"
            android:padding="@dimen/activity_horizontal_margin"
            android:text="@string/forgot_password_msg"
            android:textColor="@android:color/white"
            android:textSize="14dp" />

        <android.support.design.widget.TextInputLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <EditText
                android:id="@+id/email"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginBottom="10dp"
                android:layout_marginTop="20dp"
                android:hint="@string/hint_email"
                android:inputType="textEmailAddress"
                android:textColor="@android:color/white"
                android:textColorHint="@android:color/white" />
        </android.support.design.widget.TextInputLayout>

        <!-- Login Button -->

        <Button
            android:id="@+id/btn_reset_password"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="20dip"
            android:background="@color/colorAccent"
            android:text="@string/btn_reset_password"
            android:textColor="@android:color/black" />

        <Button
            android:id="@+id/btn_back"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            android:background="@null"
            android:text="@string/btn_back"
            android:textColor="@color/colorAccent" />

    </LinearLayout>

    <ProgressBar
        android:id="@+id/progressBar"
        android:layout_width="30dp"
        android:layout_height="30dp"
        android:layout_gravity="center|bottom"
        android:layout_marginBottom="20dp"
        android:visibility="gone" />
</android.support.design.widget.CoordinatorLayout>

13. Open ResetPasswordActivity.java add the below code. You can use sendPasswordResetEmail() method to send the password reset email.

package info.androidhive.firebase;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;

public class ResetPasswordActivity extends AppCompatActivity {

    private EditText inputEmail;
    private Button btnReset, btnBack;
    private FirebaseAuth auth;
    private ProgressBar progressBar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_reset_password);

        inputEmail = (EditText) findViewById(R.id.email);
        btnReset = (Button) findViewById(R.id.btn_reset_password);
        btnBack = (Button) findViewById(R.id.btn_back);
        progressBar = (ProgressBar) findViewById(R.id.progressBar);

        auth = FirebaseAuth.getInstance();

        btnBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        btnReset.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                String email = inputEmail.getText().toString().trim();

                if (TextUtils.isEmpty(email)) {
                    Toast.makeText(getApplication(), "Enter your registered email id", Toast.LENGTH_SHORT).show();
                    return;
                }

                progressBar.setVisibility(View.VISIBLE);
                auth.sendPasswordResetEmail(email)
                        .addOnCompleteListener(new OnCompleteListener<Void>() {
                            @Override
                            public void onComplete(@NonNull Task<Void> task) {
                                if (task.isSuccessful()) {
                                    Toast.makeText(ResetPasswordActivity.this, "We have sent you instructions to reset your password!", Toast.LENGTH_SHORT).show();
                                } else {
                                    Toast.makeText(ResetPasswordActivity.this, "Failed to send reset email!", Toast.LENGTH_SHORT).show();
                                }

                                progressBar.setVisibility(View.GONE);
                            }
                        });
            }
        });
    }

}
android-firebase-forgot-password

Here is the password reset email user will receive.

android-firebase-reset-password-email

Below are the quick code snippets to other user functionalities.

Checking User Session

auth = FirebaseAuth.getInstance();
        if (auth.getCurrentUser() != null) {
            // User is logged in
        }

Change Password

FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();

user.updatePassword(newPassword.getText().toString().trim())
            .addOnCompleteListener(new OnCompleteListener<Void>() {
        @Override
        public void onComplete(@NonNull Task<Void> task) {
            if (task.isSuccessful()) {
                Toast.makeText(MainActivity.this, "Password is updated!", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(MainActivity.this, "Failed to update password!", Toast.LENGTH_SHORT).show();
                progressBar.setVisibility(View.GONE);
            }
        }
    });

Change Email

FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();

user.updateEmail(newEmail.getText().toString().trim())
            .addOnCompleteListener(new OnCompleteListener<Void>() {
        @Override
        public void onComplete(@NonNull Task<Void> task) {
            if (task.isSuccessful()) {
                Toast.makeText(MainActivity.this, "Email address is updated.", Toast.LENGTH_LONG).show();
            } else {
                Toast.makeText(MainActivity.this, "Failed to update email!", Toast.LENGTH_LONG).show();
            }
        }
    });

Deleting Account / User

FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user != null) {
        user.delete()
                .addOnCompleteListener(new OnCompleteListener<Void>() {
                    @Override
                    public void onComplete(@NonNull Task<Void> task) {
                        if (task.isSuccessful()) {
                            Toast.makeText(MainActivity.this, "Your profile is deleted:( Create a account now!", Toast.LENGTH_SHORT).show();
                        } else {
                            Toast.makeText(MainActivity.this, "Failed to delete your account!", Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }

Sign Out

auth.signOut();

// this listener will be called when there is change in firebase user session
FirebaseAuth.AuthStateListener authListener = new FirebaseAuth.AuthStateListener() {
            @Override
            public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
                FirebaseUser user = firebaseAuth.getCurrentUser();
                if (user == null) {
                    // user auth state is changed - user is null
                    // launch login activity
                    startActivity(new Intent(MainActivity.this, LoginActivity.class));
                    finish();
                }
            }
        };

2.4 Profile Screen – Putting All Together

Now we’ll keep all the above functionalities in main activity and make fully functional app. Open the layout file of main activity activity_main.xml and add the below layout code.

14.Open the activity_main.xml and add the following code.

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout 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:fitsSystemWindows="true"
    tools:context=".MainActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay"
        app:elevation="0dp">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimaryDark"
            app:layout_scrollFlags="scroll|enterAlways"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

    </android.support.design.widget.AppBarLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:paddingBottom="@dimen/activity_vertical_margin"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:paddingTop="@dimen/activity_vertical_margin"
        app:layout_behavior="@string/appbar_scrolling_view_behavior">

        <EditText
            android:id="@+id/old_email"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="@string/hint_email"
            android:inputType="textEmailAddress"
            android:maxLines="1"
            android:singleLine="true" />

        <EditText
            android:id="@+id/new_email"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="@string/hint_new_email"
            android:inputType="textEmailAddress"
            android:maxLines="1"
            android:singleLine="true" />

        <EditText
            android:id="@+id/password"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:focusableInTouchMode="true"
            android:hint="@string/prompt_password"
            android:imeActionId="@+id/login"
            android:imeOptions="actionUnspecified"
            android:inputType="textPassword"
            android:maxLines="1"
            android:singleLine="true" />

        <EditText
            android:id="@+id/newPassword"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:focusableInTouchMode="true"
            android:hint="@string/new_pass"
            android:imeActionId="@+id/login"
            android:imeOptions="actionUnspecified"
            android:inputType="textPassword"
            android:maxLines="1"
            android:singleLine="true" />

        <Button
            android:id="@+id/changeEmail"
            style="?android:textAppearanceSmall"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="16dp"
            android:background="@color/colorPrimaryDark"
            android:text="@string/btn_change"
            android:textColor="@android:color/white"
            android:textStyle="bold" />

        <Button
            android:id="@+id/changePass"
            style="?android:textAppearanceSmall"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="16dp"
            android:background="@color/colorPrimaryDark"
            android:text="@string/btn_change"
            android:textColor="@android:color/white"
            android:textStyle="bold" />

        <Button
            android:id="@+id/send"
            style="?android:textAppearanceSmall"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="16dp"
            android:background="@color/colorPrimaryDark"
            android:text="@string/btn_send"
            android:textColor="@android:color/white"
            android:textStyle="bold" />

        <ProgressBar
            android:id="@+id/progressBar"
            android:layout_width="30dp"
            android:layout_height="30dp"
            android:visibility="gone" />

        <Button
            android:id="@+id/remove"
            style="?android:textAppearanceSmall"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="16dp"
            android:background="@color/colorPrimaryDark"
            android:text="@string/btn_remove"
            android:textColor="@android:color/white"
            android:textStyle="bold" />

        <Button
            android:id="@+id/change_email_button"
            style="?android:textAppearanceSmall"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="16dp"
            android:text="@string/change_email"
            android:textStyle="bold" />

        <Button
            android:id="@+id/change_password_button"
            style="?android:textAppearanceSmall"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="16dp"
            android:text="@string/change_password"
            android:textStyle="bold" />

        <Button
            android:id="@+id/sending_pass_reset_button"
            style="?android:textAppearanceSmall"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="16dp"
            android:text="@string/send_password_reset_email"
            android:textStyle="bold" />

        <Button
            android:id="@+id/remove_user_button"
            style="?android:textAppearanceSmall"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="16dp"
            android:text="@string/remove_user"
            android:textStyle="bold" />

        <Button
            android:id="@+id/sign_out"
            style="?android:textAppearanceSmall"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="16dp"
            android:background="@color/colorPrimary"
            android:text="@string/btn_sign_out"
            android:textColor="@android:color/white"
            android:textStyle="bold" />

    </LinearLayout>

</android.support.design.widget.CoordinatorLayout>

15. Open the MainActivity.java and the following code. Basically here we combine all the functionalities into a single activity.

package info.androidhive.firebase;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;

public class MainActivity extends AppCompatActivity {

    private Button btnChangeEmail, btnChangePassword, btnSendResetEmail, btnRemoveUser,
            changeEmail, changePassword, sendEmail, remove, signOut;

    private EditText oldEmail, newEmail, password, newPassword;
    private ProgressBar progressBar;
    private FirebaseAuth.AuthStateListener authListener;
    private FirebaseAuth auth;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        toolbar.setTitle(getString(R.string.app_name));
        setSupportActionBar(toolbar);

        //get firebase auth instance
        auth = FirebaseAuth.getInstance();

        //get current user
        final FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();

        authListener = new FirebaseAuth.AuthStateListener() {
            @Override
            public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
                FirebaseUser user = firebaseAuth.getCurrentUser();
                if (user == null) {
                    // user auth state is changed - user is null
                    // launch login activity
                    startActivity(new Intent(MainActivity.this, LoginActivity.class));
                    finish();
                }
            }
        };

        btnChangeEmail = (Button) findViewById(R.id.change_email_button);
        btnChangePassword = (Button) findViewById(R.id.change_password_button);
        btnSendResetEmail = (Button) findViewById(R.id.sending_pass_reset_button);
        btnRemoveUser = (Button) findViewById(R.id.remove_user_button);
        changeEmail = (Button) findViewById(R.id.changeEmail);
        changePassword = (Button) findViewById(R.id.changePass);
        sendEmail = (Button) findViewById(R.id.send);
        remove = (Button) findViewById(R.id.remove);
        signOut = (Button) findViewById(R.id.sign_out);

        oldEmail = (EditText) findViewById(R.id.old_email);
        newEmail = (EditText) findViewById(R.id.new_email);
        password = (EditText) findViewById(R.id.password);
        newPassword = (EditText) findViewById(R.id.newPassword);

        oldEmail.setVisibility(View.GONE);
        newEmail.setVisibility(View.GONE);
        password.setVisibility(View.GONE);
        newPassword.setVisibility(View.GONE);
        changeEmail.setVisibility(View.GONE);
        changePassword.setVisibility(View.GONE);
        sendEmail.setVisibility(View.GONE);
        remove.setVisibility(View.GONE);

        progressBar = (ProgressBar) findViewById(R.id.progressBar);

        if (progressBar != null) {
            progressBar.setVisibility(View.GONE);
        }

        btnChangeEmail.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                oldEmail.setVisibility(View.GONE);
                newEmail.setVisibility(View.VISIBLE);
                password.setVisibility(View.GONE);
                newPassword.setVisibility(View.GONE);
                changeEmail.setVisibility(View.VISIBLE);
                changePassword.setVisibility(View.GONE);
                sendEmail.setVisibility(View.GONE);
                remove.setVisibility(View.GONE);
            }
        });

        changeEmail.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                progressBar.setVisibility(View.VISIBLE);
                if (user != null && !newEmail.getText().toString().trim().equals("")) {
                    user.updateEmail(newEmail.getText().toString().trim())
                            .addOnCompleteListener(new OnCompleteListener<Void>() {
                                @Override
                                public void onComplete(@NonNull Task<Void> task) {
                                    if (task.isSuccessful()) {
                                        Toast.makeText(MainActivity.this, "Email address is updated. Please sign in with new email id!", Toast.LENGTH_LONG).show();
                                        signOut();
                                        progressBar.setVisibility(View.GONE);
                                    } else {
                                        Toast.makeText(MainActivity.this, "Failed to update email!", Toast.LENGTH_LONG).show();
                                        progressBar.setVisibility(View.GONE);
                                    }
                                }
                            });
                } else if (newEmail.getText().toString().trim().equals("")) {
                    newEmail.setError("Enter email");
                    progressBar.setVisibility(View.GONE);
                }
            }
        });

        btnChangePassword.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                oldEmail.setVisibility(View.GONE);
                newEmail.setVisibility(View.GONE);
                password.setVisibility(View.GONE);
                newPassword.setVisibility(View.VISIBLE);
                changeEmail.setVisibility(View.GONE);
                changePassword.setVisibility(View.VISIBLE);
                sendEmail.setVisibility(View.GONE);
                remove.setVisibility(View.GONE);
            }
        });

        changePassword.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                progressBar.setVisibility(View.VISIBLE);
                if (user != null && !newPassword.getText().toString().trim().equals("")) {
                    if (newPassword.getText().toString().trim().length() < 6) {
                        newPassword.setError("Password too short, enter minimum 6 characters");
                        progressBar.setVisibility(View.GONE);
                    } else {
                        user.updatePassword(newPassword.getText().toString().trim())
                                .addOnCompleteListener(new OnCompleteListener<Void>() {
                                    @Override
                                    public void onComplete(@NonNull Task<Void> task) {
                                        if (task.isSuccessful()) {
                                            Toast.makeText(MainActivity.this, "Password is updated, sign in with new password!", Toast.LENGTH_SHORT).show();
                                            signOut();
                                            progressBar.setVisibility(View.GONE);
                                        } else {
                                            Toast.makeText(MainActivity.this, "Failed to update password!", Toast.LENGTH_SHORT).show();
                                            progressBar.setVisibility(View.GONE);
                                        }
                                    }
                                });
                    }
                } else if (newPassword.getText().toString().trim().equals("")) {
                    newPassword.setError("Enter password");
                    progressBar.setVisibility(View.GONE);
                }
            }
        });

        btnSendResetEmail.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                oldEmail.setVisibility(View.VISIBLE);
                newEmail.setVisibility(View.GONE);
                password.setVisibility(View.GONE);
                newPassword.setVisibility(View.GONE);
                changeEmail.setVisibility(View.GONE);
                changePassword.setVisibility(View.GONE);
                sendEmail.setVisibility(View.VISIBLE);
                remove.setVisibility(View.GONE);
            }
        });

        sendEmail.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                progressBar.setVisibility(View.VISIBLE);
                if (!oldEmail.getText().toString().trim().equals("")) {
                    auth.sendPasswordResetEmail(oldEmail.getText().toString().trim())
                            .addOnCompleteListener(new OnCompleteListener<Void>() {
                                @Override
                                public void onComplete(@NonNull Task<Void> task) {
                                    if (task.isSuccessful()) {
                                        Toast.makeText(MainActivity.this, "Reset password email is sent!", Toast.LENGTH_SHORT).show();
                                        progressBar.setVisibility(View.GONE);
                                    } else {
                                        Toast.makeText(MainActivity.this, "Failed to send reset email!", Toast.LENGTH_SHORT).show();
                                        progressBar.setVisibility(View.GONE);
                                    }
                                }
                            });
                } else {
                    oldEmail.setError("Enter email");
                    progressBar.setVisibility(View.GONE);
                }
            }
        });

        btnRemoveUser.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                progressBar.setVisibility(View.VISIBLE);
                if (user != null) {
                    user.delete()
                            .addOnCompleteListener(new OnCompleteListener<Void>() {
                                @Override
                                public void onComplete(@NonNull Task<Void> task) {
                                    if (task.isSuccessful()) {
                                        Toast.makeText(MainActivity.this, "Your profile is deleted:( Create a account now!", Toast.LENGTH_SHORT).show();
                                        startActivity(new Intent(MainActivity.this, SignupActivity.class));
                                        finish();
                                        progressBar.setVisibility(View.GONE);
                                    } else {
                                        Toast.makeText(MainActivity.this, "Failed to delete your account!", Toast.LENGTH_SHORT).show();
                                        progressBar.setVisibility(View.GONE);
                                    }
                                }
                            });
                }
            }
        });

        signOut.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                signOut();
            }
        });

    }

    //sign out method
    public void signOut() {
        auth.signOut();
    }

    @Override
    protected void onResume() {
        super.onResume();
        progressBar.setVisibility(View.GONE);
    }

    @Override
    public void onStart() {
        super.onStart();
        auth.addAuthStateListener(authListener);
    }

    @Override
    public void onStop() {
        super.onStop();
        if (authListener != null) {
            auth.removeAuthStateListener(authListener);
        }
    }
}
android-firebase-profile-activity

Now you have the basics for creating a simple login / register app with firebase. You can continue exploring firebase as it offers much more functionalities and it’s fun to use them.

Ravi is hardcore Android programmer and Android programming has been his passion since he compiled his first hello-world program. Solving real problems of Android developers through tutorials has always been interesting part for him.
  • Jeffrey Nyauke

    Thanks Ravi, was really waiting for this!

    • Jeffrey Nyauke

      But what if you want to store more details about the user take for example profilepic

      • You need to createUser() – instead of creating him with email and password alone.

        • Jeffrey Nyauke

          I dont understand, you mean I should create a function called createUser() that stores in a separate database and host?

          • No, Firebase provides createUser() method. Check their docs.

  • Shivraj Vala

    Please Ravibhai upload chat and database sample of firebase and XMPP

    • It would be very big project. You can follow my older article using GCM and convert it to firebase

  • Trey Rosius

    Hi Ravi, can a client server app like say instagram be created and deployed using just firebase?Using just firebase REST API, no php scripts?

    • It can be, but you need to pay for the hosting space / file space.

      • Trey Rosius

        just like you need to pay for hosting and space on digital ocean too…Thanks for the Clarification

        • Yeah, but you can prefer using Google Services as they much reliable and faster.

  • Sandeep

    Hi there!

    I could not able to load jar file in my gradle.
    compile “com.google.firebase:firebase-auth:9.0.2”
    Please help me!

  • Ravikant paudel

    Thanks Ravi bro
    How can i send verification email when user register?
    i read doc but don’t find for android.

  • Ralry Ong

    thanks Ravi for research this technology and post out.

  • Malik Qirtas Awan

    If our app has a lot of users like in thousands then is it free for registering/login services for all users?

    • Free!
      https://firebase.google.com/pricing/

      Which products are paid? Which are free?

      Firebase’s paid infrastructure products are the Realtime Database, Firebase Storage, Hosting, and Test Lab. We offer a free tier for all of these products except Test Lab.

      Firebase also has many free products: Analytics, Notifications, Crash Reporting, Authentication, Remote Config, Dynamic Links, Firebase Invites, and App Indexing. You can use an unlimited amount of these in all plans, including our free Spark Plan.

  • Danh Nguyễn

    Hi, Ravi Tamada
    I want to get list user register account on firebase. Can I get them? I don’t see any document about it

    • You want to list all the registered users in android app?

      • Danh Nguyễn

        Yes. Could you help me?

      • Danh Nguyễn

        Yes, any way to do that?

  • Aarav Choudhary

    Hello Sir I have problem in the Login Activity its showing you cannot find the symbol setContentView(R.layout.activity_login);

    its showing R in red color

    • Aarav Choudhary

      D:AndroidFirebaseAppappsrcmainreslayoutactivity_main.xml
      Error:(16) No resource identifier found for attribute ‘layout_scrollFlags’ in package ‘info.pradeep.firebaseapp’
      Error:(26) No resource identifier found for attribute ‘layout_behavior’ in package ‘info.pradeep.firebaseapp’
      Error:(13, 20) No resource found that matches the given name (at ‘theme’ with value ‘@style/AppTheme.AppBarOverlay’).
      Error:(22, 25) No resource found that matches the given name (at ‘popupTheme’ with value ‘@style/AppTheme.PopupOverlay’).
      Error:(34, 26) No resource found that matches the given name (at ‘layout_behavior’ with value ‘@string/appbar_scrolling_view_behavior’).
      Error:(59, 23) No resource found that matches the given name (at ‘hint’ with value ‘@string/prompt_password’).
      Error:Execution failed for task ‘:app:processDebugResources’.
      > com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException: Process ‘command ‘C:UsersAndroidAppDataLocalAndroidSdkbuild-tools24.0.0aapt.exe” finished with non-zero exit value 1

      • Dheeraj Parashar

        Just remove the attributes that are causing the errors. They are not important, your application will run just fine.

    • Check the .R import statement at the top.

      • Aarav Choudhary

        where to check actually i am beginner

      • Aarav Choudhary

        Error:(11) No resource identifier found for attribute ‘layout_behavior’ in package ‘info.pradeep.firebaseapp’
        Error:(19, 26) No resource found that matches the given name (at ‘layout_behavior’ with value ‘@string/appbar_scrolling_view_behavior’).
        Error:Execution failed for task ‘:app:processDebugResources’.
        > com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException: Process ‘command ‘C:UsersAndroidAppDataLocalAndroidSdkbuild-tools24.0.0aapt.exe” finished with non-zero exit value 1

        what does these means

  • Abdel

    Hello !
    Thanks again Sir for this tremendous work.
    Regards

  • Edward

    Hi Ravi,

    Great tutorial! Unfortunately however it doesn’t cover for someone signing up with the same email…it crashes. I thought I’d just let you know.

    Thanks again!

  • sunny

    HI,
    could you please show me a way to start work on developing android antivirus.

    or can you help me to give a basi idea and flow to start work on it. like basic concepts and basic keywords to search on google ?

  • wisnu kurniawan

    waw its complette

  • Macharia

    Hi Ravi can you write on storing binary files on Firebase(images and files)they are now supporting it..,

  • Naqib Shayea Qazizadah

    Hi Ravi thanks for nice tutorials bro I want to know if I can implement this login and register method on my existing application? In my application after the user logs in he can post something and it goes to my own server.
    I want to know if this is good for this kind of application?

  • omar

    Appear to me in logcat [FirebaseApp initialization unsuccessful] i use your source code , and change google-server.json , what is the problam

  • Sandeep

    Great tutorial to start with Firebase. Firebase also supports Google and Facebook Login i guess. Found a good tutorial on Firebase facebbok Login. http://androidbash.com/firebase-facebook-login-tutorial-android/

  • Manish Kumar

    Hey Ravi, Nice tutorial. Thanks . But i am getting an error.

    FAILURE: Build failed with an exception.

    * What went wrong:

    Execution failed for task ‘:app:processDebugGoogleServices’.

    > No matching client found for package name ‘info.androidhive.welcomeslider’

    • Manny264

      what package name did you use when creating the application?

  • Nice tutorial, would love to request you for an tutorial on FCM, https://support.google.com/googleplay/android-developer/answer/2663268

  • Nidhin Kumar

    Hi ravi,
    I was just waiting for this tutorial can we expect somemore tutorials using firebase like inserting the datas as well as reading those datas from firebase

  • pm abi

    Has any of your applications ever hit 50 concurrent connections hard limit while using the free spark plan??
    The out of the box solutions looks promising for porting my application right away..But concerned of this small problem

  • Manish Kumar

    Hey can you make a tutorial on how to make a booking calendar on an android app

    • Do you mean calendar view or calendar event ?

      • Manish Kumar

        Lets say my customer has taken food subscription for a month. they want to cancel few days out of that . A calendar to do that and they should not be able to pick up a date before todays date. any date before todays date should be blacked out , so that customers cannot select those dates.

  • Walaa’ Hamdy Assy

    there are one replication and a simple mistake that could confuse some of us in the login activity and some xml files at tools:context
    appreciate it

    • Hi Walla

      Can you tell me what it is. So that I can correct it.

      • Walaa’ Hamdy Assy

        hi ravi. they are just in the article the apk and completed code work just fine
        i will take some snapshots and highlight the errors , but where to post them?
        eg: the tools context in some layout files refer to another activity not the right one

      • Urja Pawar

        Hi Ravi!, the correction is -> In xml of ResetPasswordActivity, it should be tools:context=”info.androidhive.firebase.ResetPasswordActivity” instead of tools:context=”info.androidhive.firebase.LoginActivity”

        • Yeah, It is copy / paste error. But it won’t cause any problem.

  • venkatesh

    Great tutorial:)
    Can you help me with this error:
    i cant move to the signup page from login page on clicking”get registered in Firebase” button.It says Null pointer exception:trying to invoke virtual method ‘void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)’ on a null object reference in the logcat.Everything else works fine.

  • Aiman Baharum

    Always the best bro

  • Podster

    The download source code does not work. It goes to the download page but nothing gets downloaded, even if you logged in.

    Thanks.

  • Abhishek Kumar

    Sir,

    I am using fragment for the designing of the firebase simple login registration.

    I get error in the OnCreateView() method on initializing

    auth = FirebaseAuth.getInstance();

    error:- Error:(58, 28) error: cannot access zzaja
    class file for com.google.android.gms.internal.zzaja not found.

    please help on this(stick for more than an hour).

    • Dheeraj Parashar

      Check your gradle files to see if have properly imported everything or not.

      • Abhishek Kumar

        I already checked it everything is fine as described here.

    • Amar Bakir

      I solved this exact problem today and stumbled onto this unanswered question by chance during the process.

      First, ensure you’ve properly setup Firebase for Android as documented here: https://firebase.google.com/docs/android/setup. Then, make sure you are compiling the latest version of the Firebase APIs (9.2.0) and the Google Play Services APIs (9.2.0) that you are using. My gradle dependencies look something like this:

      dependencies {

      compile ‘com.google.android.gms:play-services-location:9.2.0’
      compile ‘com.google.firebase:firebase-core:9.2.0’
      compile ‘com.google.firebase:firebase-auth:9.2.0’
      compile ‘com.google.firebase:firebase-messaging:9.2.0’
      }

      Hope this helps!

  • Mostafa Anter

    are you have any idea to how push notification from android to android device by using firebase push notification

  • Ravi Kumar

    its a kind request , you have till now tought us about how to log in and all . it will b very helpfull if u can show how to set up user profile after that . means login in though email id and password after that a create profile page in which we let them set their images and name and store all the information on database

  • atul o holic

    Awesome tutorial man. Cheers to you and Thank you 🙂

    Just a small thing which I found, the below piece of code is called twice in the LoginActivity class, not sure if its there purposely.

    //Get Firebase auth instance
    auth = FirebaseAuth.getInstance();

    • PINKesh Darji

      Just comment out any one.

  • MITEN SHAH

    Heyyy… I am getting an error while gradle sync.
    It shows Failed to resolve: com.google.firebase.firebase-auth:9.0.2
    please help

    • Praneeth Chowdary

      It seems that u haven’t installed the “Google Repository”
      First install it in the SDKmanager>Extras>GoogleRepository

      • MoHit KaUsh!k

        i think this is maybe my android studio version 2.1.2 ??

        • Praneeth Chowdary

          It doesn’t matter in what version you are developing
          I’m also using the sae version

  • Afif FirZil

    Hai sir, how can we know that database in firebase cloud has been changed while the app is in background or inactive? how to give notification to device while user not open the app if there is new data?

  • Eyal Engel

    Hi Ravi, amazing guide! I learned a lot, thank you!
    One question please – if I have a facebook Login button – then how do you I save the user in Firebase? I only have his email but not a password.
    Thanks!

  • Urja Pawar

    “Failed to update email”, I am not able to update email and password , it shows this error “Failed to load module descriptor class: Didn’t find class “com.google.android.gms.dynamite.descriptors.com.google.firebase.auth.ModuleDescriptor” on path: DexPathList[[zip file “/data/app/com.urjapawar.assistodo-1/base.apk”],nativeLibraryDirectories=[/vendor/lib64, /system/lib64]]”

  • Izi

    Hi Ravi thanks for your really great tutorial, I am having this issue when I try to make a build: Error:(45, 54) error: cannot find symbol variable toolbar, the error is located in LoginActivity.java with the code : Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar); thanks for your help

    • PINKesh Darji

      This is because you have no toolbar with id toolbar in layout xml file.
      Comment out both line in LoginActivity.java and you are done.
      // Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
      // setSupportActionBar(toolbar);

  • Dilpreet

    import com.google.firebase.auth.FirebaseAuth;
    Getting an error on FIREBASEAUTH.
    PLZ help me on this

    • Praneeth Chowdary

      First u have to install the “Google Repository” in the SDK manager then rebuild the project

      • Mohit

        can’t resolve com.google.firebase.auth.FirebaseAuth ?????

        • Praneeth Chowdary

          U have to the add the following code
          dependencies {
          compile ‘com.firebase:firebase-client-android:2.5.2+’
          }

          In the build.gradle
          Then rebuild the project
          If this doesn’t help you feel free to ask……..😃

          • MoHit KaUsh!k

            i think this is maybe my android studio version 2.1.2 ??????

  • Prashant

    Another great tutorial……..thank you

  • Praneeth Chowdary

    When I click the Register Button and Login me Button the app closes is there any solution for it……?
    can anyone provide the manifest file for this application

  • Rahul Deewan

    Hello Ravi. Thanks for a very good tutorial. I would like to know one thing that how to store user profile in Firebase database along with the user’s Email and Password.

  • Mohit

    can’t resolve com.google.firebase.auth.FirebaseAuth ?????

    • Cristian Gonzalez

      compile “com.google.firebase:firebase-auth:9.0.2”

  • Nick Theinvincibleprints

    Hi Ravi…great tutorial but could you please come up with loging in with Facebook and simple login tutorial all in one. Thanks

    • Junie Negentien

      I found some resources in the Internet but its not a clear tutorial. Did you find something better?

  • Mary Mathew

    plz come with tutorial on FCM,

  • Ayush Shrivastava

    Error:(15, 0) Could not find property ‘build’ on root project ‘Firebase’.

  • nikhil bhoyar

    Again Great Tutorial ,
    but can anyone tell how to set our own mail server to reset password .

    • sar

      All mail sever related options are located on the firebase console.
      console.firebase.google.com

  • neelam

    replace your play-service version by compile ‘com.google.android.gms:play-services-auth:9.0.2’ gradle file

  • Aniket

    Sir, DefaultHttpClient is not working in SDK version 23 , buildToolsVersion 23.0.3 and using Marshmallow 6.0. Please suggest the correct way to handle this.

  • dhruv thakker

    i created account with id asdf@sty.com password asdfghjkl where do i get the reset link how can i see that email

    • sar

      should be on your email you registered with

      • dhruv thakker

        if it means the account where i got firebase services.json file than no it is not there

  • Purvik Rana

    I have put Firebase Authentication in one of my application. Now what i’m facing, every time when i close my app and ope it again, it will popup login window again. What that means actually!! Is it signing out the user when we close the application? Reply with the Answer ASAP.:)

  • Ayush

    Can someone tell me how to implement these account settings in overflow menu?

  • artye

    thanks for this nice tutorial it is working. Can I also store the user name.

  • Santosh Yadav

    awesome tutorial nice one …. can we aspect next one for FCM… coz waiting for that desperately

  • Madhur Jain

    Nice tutorial but i want to ask few Question
    1) can we create multiple table in firebase.
    2) can we apply join on the tables in firebase.

    • King Kazma

      Firebase using noSql database so theres no multiple table or any join operation

  • John.

    Hi guys, I’m getting this error “Authentication failed.com.google.firebase.firebaseException:…” after testing the signup activity using my Emulator. Anyone help!

  • Junie Negentien

    Hi, RAvi.. this one is nice tutorial. Can you make another one with combination og Facebook & Gmail account log in.

  • WeekendCoder

    How to add dependencies for Android 6.0.0?

  • Anshul Verma

    Sir, is there any tutorial using facebook login using firebase ?
    please ping me!

  • Mahesh Mohan

    how to use both SHA release and
    debug…..can i used it at a time.

  • Karandeep Atwal

    Very Nice Informative tutorial

  • Obayi Bright

    Hello,

    I have followed your guide but I keep encountering problems, the full description which can be found in the link below. I’d really like your help in resolving this issue.

    http://stackoverflow.com/questions/38925754/my-firebase-authentication-dependency-issue

    Thank you for your anticipated help..

  • Gungde Aditya

    Awesome Tutorial, I want ask a few question about this:
    1. Can we add some another field, like Name, Phone etc..
    2. The data that stored on Firebase Console can sync into our hosting database or not ?

    • Me

      Yes you can and pass those field values in to the database tree..
      Dont really understand the second question but i know that your firebase console also provides a database..(json tree database)

      • News Popofiere

        Hello Me i’m new in the android developement and firebase, but if i want to make a chat app like whattsapp can i do it with only firebase? Many Thanks

  • Vikas Kumar

    Awesome Tutorial man but I am getting this error java.lang.IllegalStateException: FirebaseApp with name [DEFAULT] doesn’t exist. please help

    • As per latest updates the google services plugin should be added at the bottom of the file

      apply plugin: ‘com.google.gms.google-services’

      http://stackoverflow.com/questions/37342403/firebaseapp-with-name-default-doesnt-exist

      http://stackoverflow.com/questions/37346363/java-lang-illegalstateexception-firebaseapp-with-name-default

      • Vikas Kumar

        thanks for the reply but tell me one thing google play service version should be same firebase version these are my dependencies dependencies {
        compile fileTree(dir: ‘libs’, include: [‘*.jar’])
        compile ‘com.android.support:appcompat-v7:23.2.0’
        compile ‘com.google.firebase:firebase-auth:9.2.0’
        compile ‘com.google.firebase:firebase-database:9.2.0’
        compile ‘com.google.android.gms:play-services-location:9.2.0’

        }
        apply plugin: ‘com.google.gms.google-services’

        tell me if i am doing anything wrong I am getting this error W/DynamiteModule: Local module descriptor class for com.google.firebase.auth not found.

      • Vikas Kumar

        thanks for the reply but I am still getting this error
        Local module descriptor class for com.google.firebase.auth not found.
        and these are my dependencies

        dependencies {
        compile fileTree(dir: ‘libs’, include: [‘*.jar’])
        compile ‘com.android.support:appcompat-v7:23.2.0’
        compile ‘com.google.firebase:firebase-auth:9.2.0’
        compile ‘com.google.firebase:firebase-database:9.2.0’
        compile ‘com.google.android.gms:play-services-location:9.2.0’

        }
        apply plugin: ‘com.google.gms.google-services’

  • Vikas Kumar

    Awesome tutorial man but i am getting this error
    W/DynamiteModule: Local module descriptor class for com.google.firebase.auth not found. when i am trying to click on login button

  • What an awesome post thanks!
    I have an one question that how to record video demo shows mobile UI nicely like yours?
    Is there any tool?
    Please recommend any tool or method to record demo videos.
    thanks

    • aas

      You can use CamStudio

      • Thanks
        but CamStudio is just record and capture tool.
        I want to know mirroring tool that can mirror my Android device on PC like this demo video.

        • You have to record the video using android app. Use camtasia studio to edit the video. Use any mobile skin .png file and place the recorded video on top of it.

  • ‫إليود نجوغونا‬‎

    Thanks for the Tutorial but my app did not run because the Google Play Services in my Emulator is out of date..I have tried everything thats has been said in almost all chats and tutorial but i haven’t found any solution to that.Am welcoming any suggestions

    • Zubair Ahmad

      where you have a problem dear ?

      • ‫إليود نجوغونا‬‎

        The Tutorial was amazing ..but am having issues updating my Google Play Services in my Emulator…whenever i try to login or signup the emulator pops up a message “The App won’t run unless you update Google Play Services”

  • Zubair Ahmad

    Thanks a lot its very halpfull for me

  • ASR

    Thanks for the tutorial. but i cant able to access my data after adding user and logging in. i have a criteria that by using the child name i need to get my data from firebase. but i am not able to get that please help me its urgent please it my humble request. any one can help me in this. what should i do now please help me.

  • ketan sethi

    Thanks! Thanks! Thanks! so much..implemented successfully 🙂

  • Mohit Khaitan

    Hey Ravi, you have shown only two credentials that are getting saved in the database. What if I have to save other credentials like Username, Phone, etc. Please help me out with this !!

  • Hillarie Kip

    Hey Ravi,I followed your tutorial and it works very well when i sign in with android emulator or even bluestacks….but when i use real device i cant sign in giving me firebase network error…

    • Sandeep

      Just check if your device is connected to internet and all the required permission are given in manifest.

      • Hillarie Kip

        hello Sandeep my device is connected to internet and i have this permissions:

        but still i cant connect firebase through real device..but when i use wifi connection it works well…just 3g connection doesnt work…Help

  • You are Best 🙂

  • prasanth s

    hi ravi, i have some error
    can u plz give solutions? …everything i have applied ur code and gradle also build successfully but after installation of apk it shows “unfortunately firebase auth stopped.”.

    • Check LogCat for errors.

      • prasanth s

        hi, i m also need to store user name and mobile number .. so plz tell me how to do.

        • Sandeep

          After login/register success you have to get the current user and update the name. If you want to add extra info like mobile no, address etc then you have to create a separate doc and save like that.

      • prasanth s

        thanks dude.its toolbar error

  • Kevin

    how can i download the code or where do i sign up?

    • The download code button is present at the top of the article. Use Google, facebook or other options to sign up and download.

  • Mandeep Singh Aulakh

    hello Ravi i am follow all your code and thanks for all the code it help alot.
    I want to add my firebase url in the app for testing purpose but cannot find where to put json file and url in the app
    please help me….
    becoz i am new in android firebase.

    • You don’t have to put any firebase url in the project. Instead you need to add the google-services.json file downloaded from your firebase console. Using this file the app automatically connected to your firebase app.

      • Mandeep Singh Aulakh

        Thanks for the help

  • Shubham Tyagi

    hello there…
    really awesome tutorial…just need some more help…in the registration activity….i also want to take user name, mobile no, address, etc…with the email id and password…and when the user login….i want to display that information….how can i do that..please help…

  • kirti

    plz helpmehow can i resolve the jeson file missing error

  • Android Dethshot

    sign in working but sign up isn’t it will give error in debuging console E/UncaughtException: java.lang.NoClassDefFoundError:
    D/FirebaseCrashApiImpl: throwable java.lang.NoClassDefFoundError:

  • Lavet Adhiambo

    Hi Ravi, this is a cool tutorial but I am getting this error:Caused by: java.lang.IllegalArgumentException: Given String is empty or null.I’m I supposed to add something on my get firebase auth instance method?

  • Simone Biliato

    Hello,
    thank you for this tutorial. I have a simple question.
    Please how do I send the verification email, after a user sign up?

  • Varsha Chauhan

    Hello sir…
    tutorial is really helpful..earlier i was struggling with wamp server but working with firebase is easy.
    But i m having an error in my application. I have done exactly same but the “signup_activity.xml is giving me error “Rendering problems… Following classes could not be found: -android.support.design.widget.CoordinatorLayout ” please help me out.

  • Vinayaka SP

    Hi Ravi, I really thank you a lot for making my engineering student life easier. I have used your many tutorial to implement college projects successfully. But now I’m facing a problem in this tutorial.
    Everything is fine and error free but I’m getting error while changing password and email id.
    I have included those codes in onCreateView of fragment.
    I really not getting whats wrong.
    Please help me.

    • Are you getting any errors. What is the code you used to update the password?

      • Vinayaka SP

        the same code which you have given.
        changePassword.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
        progressBar.setVisibility(View.VISIBLE);
        if (user != null && !newPassword.getText().toString().trim().equals(“”)) {
        if (newPassword.getText().toString().trim().length() < 6) {
        newPassword.setError("Password too short, enter minimum 6 characters");
        progressBar.setVisibility(View.GONE);
        } else {

        user.updatePassword(newPassword.getText().toString().trim())
        .addOnCompleteListener(new OnCompleteListener() {
        @Override
        public void onComplete(@NonNull Task task) {
        if (task.isSuccessful()) {
        //Toast.makeText(getActivity(), “Password is updated, sign in with new password!”, Toast.LENGTH_SHORT).show();
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setMessage(“Password is updated, sign in with new password!”)
        .setTitle(“Updated!”)
        .setPositiveButton(android.R.string.ok, null);
        AlertDialog dialog = builder.create();
        dialog.show();
        signOut();
        progressBar.setVisibility(View.GONE);
        } else {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setMessage(“Failed to update password!”)
        .setTitle(“Error!”)
        .setPositiveButton(android.R.string.ok, null);
        AlertDialog dialog = builder.create();
        dialog.show();
        progressBar.setVisibility(View.GONE);
        }
        }
        });
        }
        } else if (newPassword.getText().toString().trim().equals(“”)) {
        newPassword.setError(“Enter password”);
        progressBar.setVisibility(View.GONE);
        }
        }
        });

      • Vinayaka SP

        I’m getting “Failed to update password!”

  • Navraj Singh

    Excellent tutorial. worked like a charm on first time. Good job. keep it up.

  • Lucas

    Ravi, how to store the data in a external DB, like a MySQL? Or insert the data in firebase and mysql simultaneously

    • Why do you want to do that?

      • My company for example has its data stored in SQL, and the company would like the app and the existing system share information. Is there a way out?

    • Were you able to find your way through this problem?

  • Kutbi Panki

    Hi Ravi, Nice Tutorial.
    Apart from these things i want other features like users presence, typing status and important is off line notification.
    Can you please guide me how to achieve this using firebase.

  • Android Dethshot

    Im getting this error like this

    E/AndroidRuntime: FATAL EXCEPTION: main
    Process: info.androidhive.firebase, PID: 547
    java.lang.NoClassDefFoundError: info.androidhive.firebase.Login_Activity$1$1
    at info.androidhive.firebase.Login_Activity$1.onClick(Login_Activity.java:146)
    at android.view.View.performClick(View.java:4438)
    at android.view.View$PerformClick.run(View.java:18439)
    at android.os.Handler.handleCallback(Handler.java:733)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.os.Looper.loop(Looper.java:136)
    at android.app.ActivityThread.main(ActivityThread.java:5158)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:515)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:732)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:566)
    at dalvik.system.NativeStart.main(Native Method)
    D/FirebaseCrash: Saving crash

  • Android Dethshot

    Ravi Tamada,
    The exception come with auth
    i cant create users or log with user name or password
    The exception came from this line

    auth.createUserWithEmailAndPassword(email, password)

    when i pass email, and password it says java.lang.NoClassDefFoundError:

  • Shubham Tyagi

    heyy ravi….need some help again….i am saving the data in one activity..and i want to retrieve the same data in another activity..how can i do that..please reply ASAP..

  • EL TE

    I did not receive a push notification since implementing login authentication.
    thanks for your answer.

  • Adedara Klever Olanrewaju

    hey Ravi,can other parameters be added to the method auth.createUserWithEmailAndPassword.
    And I’d suggest you giving us a tutorial on saving user data to firebase.

    Thanks

  • theGreatBren

    My progress bar is not showing.

  • jc (J r n i n)

    Hello Ravi, I’m having this problem…..

    Error:Execution failed for task ‘:app:processDebugGoogleServices’.> Missing api_key/current_key object

    how to solve it? Thank you

  • Oguzhan

    Hi Ravi, thank you very much for tutorial.
    I used navigation drawer material design with this project,
    how should I show user profile (name and email) at navheaderview?

  • saisheshu p

    Hi.. nice tutorial.. I am Signing into Google using firebase Authentication and successfully getting the ‘IdToken’ , Now i want to verify this token on my server.. I have downloaded firebase jar files and imported to my Server side project. But when i tried to verify the Token using following code.

    FirebaseOptions options = new FirebaseOptions.Builder()

    .setServiceAccount(

    new FileInputStream(“/FilePath/serviceAccount.json”))

    .setDatabaseUrl(“https://….”)

    .build();

    FirebaseApp mydoctorApp=FirebaseApp.initializeApp(options);

    final String token=”my token…………..”;

    FirebaseAuth firebaseAuth=FirebaseAuth.getInstance(my app);

    firebaseAuth.verifyIdToken(token).addOnCompleteListener(new OnCompleteListener() {

    @Override

    public void onComplete(@com.google.firebase.internal.NonNull Task task) {

    task.getException().printStackTrace();

    }

    });

    Iam getting this Exception..

    com.google.firebase.auth.FirebaseAuthException: Token is not for this app

    at com.google.firebase.auth.internal.FirebaseTokenVerifier.verifyTokenAndSignature(FirebaseTokenVerifier.java:52)

    at com.google.firebase.auth.FirebaseAuth$1.call(FirebaseAuth.java:146)

    at com.google.firebase.auth.FirebaseAuth$1.call(FirebaseAuth.java:140)

    at com.google.firebase.tasks.Tasks$1.run(Tasks.java:63)

    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)

    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)

    at java.lang.Thread.run(Thread.java:745)

    Please help me… Thanks in advance…

  • manikandan@enhandstechies.com

    waste

  • manikandan@enhandstechies.com

    not understandable

    • Café Nâu

      why?

  • Udo Klimaschewski

    Thank you, very easy to understand tutorial, which covers all the tasks needed for e-mail authentication using firebase. The Google documentation is very terse. Using your tutorial, I was able to implement authentication to my app in a few hours.

  • Nirav Jain

    Ravi you forgot to add change DisplayName option
    Its the only thing you missed in Profile

  • Busranur

    When I try to connect to Firebase via toolsFirebaseAuthentication this error ouccurs:

    Firebase A config file “C:UsersUserDesktopAndroid ProjeBookTimerappgoogle-services.json” was found, but it indicates a project ID “book-timer” that you don’t appear to have access to. Request access or delete the file in order to proceed with the connection process.

  • dsrtradefx

    Thanks for the great tutorials! I have 3small issues. On the SignUpActivity.java I am getting the error cannot resolve method createUserWithEmailAndPassword (java.lang.string, java.lang.string). On the LoginActivity.java I am getting error cannot resolve method ‘getCurrentUser ()’ and error cannot resolve method ‘signinWithEmailandPassword(java.lang.string, java.lng.string).

    Any help would be appreciated. Thanks!

    • Have you added firebase dependencies in build.gradle correctly? Or check the import statements at top in activity.

      • dsrtradefx

        Hey Ravi. Thanks for the quick assistance. I had compile ‘com.google.firebase:firebase-admin:4.0.3’ in my app gradle… I commented it out and once I worked thru some other minor errors in my app, I got it fixed. I’m not 100% sure that was the exact issue, but it is working now. Thanks again!

  • Abdul Aziz

    Thank u, work for me

  • Sachin Kale

    Thanks Ravi………

  • Hiren Gujarati

    nice tutorial but username is missing plz update and add DiplayName()

  • rahul

    hey how to find the api key?

    • Jeff Louzada

      Hi Rahul,
      please specify a little more what you are trying to do so I can try to help
      Thanks!

  • Fernando D’Angelo Pereira da S

    Hi Ravi,

    very good doc.
    I’m doing some tests with Firebase, and I didn’t find a way to validate that the user exist or is not blocked, after a first logon.

    • Hi

      Please use Stackoverflow.com to find your answers. I have no clue right now as I need to go through the firebase docs again.

  • Ron Swartz

    Thanks very much Ravi for a great article!

  • Lim

    Hi I have problem with error “import com.google.firebase.auth.AuthResult;”
    is it the AuthResult still working on it?
    https://www.dropbox.com/s/y8lhkvpmkqb8vbw/Capture1.JPG?dl=0

    • Jeff Louzada

      Had the same problem. Try putting the below within your build.gradle(Module) dependencies
      compile ‘com.google.firebase:firebase-auth:10.0.1’

  • عمرو كمال

    Hi Ravi i got this error
    error W/DynamiteModule: Local module descriptor class for com.google.firebase.auth not found

  • Dharmendra Saini

    When i import com.google.firebase.auth.FirebaseAuth package then it is show that FirebaseAuth can not resolve,What is solution?

  • Ahmet Eroglu

    Hello how can I make sure that signed up email addresses are actually valid e mail addresses? I mean I use to sendemailverification to verify account but lets say user entered “youarestupid@gmail.com” and even tho he wont get any verification mail the account is still added to authentication database, so how can we eliminate this problem to not fill database with bullshit emails?

  • Andrew Richard

    I CANT DOWNLOAD THE CODE

  • Kavan Vadaliya

    How to add sign with google on this code ?

  • Chandrasekhar Majhi

    Bro, the code is not working. Registration and login both action are not happening.

    • Kevin Tesar

      It works for me. What errors are you seeing?

  • Nishi Dixit

    Thanks! your article helped me a lot….but i wanted to ask if i want to authorise user using mobile numbers not emails then how can i do with Firebase..

    • Muhammad Afnan

      Good Question. I am having same problem.

  • Jay Joshi

    Awesome article for initial FCM learner…Helped a lot! Thank you

  • Kennedy Ndegwa

    hi ravi could you have a sample where the user can use their facebook/Gplus acc to login
    Thanks awesome Tutorial….

  • YSY

    Hi Ravi, i am a beginner,
    i have this problem when i try to register with my email account and password, after clicking the register button it shows createUserWithEmail:onComplete:false and (Authentication failed.com.google.firebase.FirebaseNetworkException:A network error occur such as timeout, interrupted connection or unreachable host has occured)

    please help advice
    thanks.

    • Abohi

      Enable sign in with email and password in the authentication tab in firebase under method.
      Hope it helps

      • YSY

        Hi, i already did but it still didnt work

    • Café Nâu

      @disqus_PHxylADiFK:disqus You must enable your internet connection before do your email and password registering 🙂

  • Shouvik Mohanta

    U rock Buddy …Its helps me a lot … Thank uuu 🙂 ….

  • Café Nâu

    Greate post! Thanks!
    Firebase sounds like a server platform that it handle all common tasks that a popular server do.
    I think the backend team will lost some tasks when use this technology, for example: account management, message pushing, storage, …. 🙂
    Do I think correctly?

  • Jibin Philip

    Hi, Iam using firebase to register a user. it works. but when i try to get the userid of the registered user from db, it shows error or null. I need the userid to update the profile

  • kamla sharma

    hello Sir,
    i want to integrate the sms api in my android application. Can you guide me how can i achieve this with android application?

  • Reuben Kaponde

    Hi great tutorial. How can i allow for the user to add more information to their profile after registering. such as profile picture, address, phone number, etc? Thanks.

  • Ciaran426

    Hi Ravi

    When I paste in the code for the LoginActivty Xml it keeps throwing up rendering problems. I have tried a few different things but cannot find the solution. errors below

    Rendering Problems Missing styles. Is the correct theme chosen for this layout? Use the Theme combo box above the layout to choose a different layout, or fix the theme style references. Failed to find style with id 0x7fff0140 in current theme (3 similar errors not shown)
    ‘Android_Tutorials/FirebaseAuthTutorial/app/src/main/res/layout/activity_signup.xml” in attribute “imeActionId” is not a valid integer

  • Sumit

    Hi Ravi,

    I tried above code many time, But when I put dependency in build.gradle(Module.app)
    I am getting error please help me. I am using 23.0.2

    My Module. file is given below

    apply plugin: ‘com.android.application’

    android {
    compileSdkVersion 23
    buildToolsVersion “23.0.2”

    defaultConfig {
    applicationId “com.example.android.myjob”
    minSdkVersion 15
    targetSdkVersion 23
    versionCode 1
    versionName “1.0”
    }
    buildTypes {
    release {
    minifyEnabled false
    proguardFiles getDefaultProguardFile(‘proguard-android.txt’), ‘proguard-rules.pro’
    }
    }
    }

    dependencies {
    compile fileTree(include: [‘*.jar’], dir: ‘libs’)
    testCompile ‘junit:junit:4.12’
    compile ‘com.android.support:appcompat-v7:23.1.1’
    compile ‘com.android.support:design:23.1.1’
    compile ‘com.google.firebase:firebase-auth:9.2.0’
    }
    apply plugin: ‘com.google.gms.google-services’

    Error:(26, 13) Failed to resolve: com.google.firebase:firebase-auth:9.2.0
    Show in FileShow in Project Structure dialog

  • Suman Ahmed

    sir can you help me to build following structure in Android and store value in firebase

    name – ________

    email – ___________

    password – ___________

    contact no – __________

    age – _________

    [register button]

  • Zaid Sirad

    hy Ravi, thanks for your hard work
    but i cant to insert code checking user session, change password, change mail, delete account and sign out?

  • Jacek Budzynski

    Hey, I’m trying to figure out how can I store additional user data (such as date of birth and full name) using Firebase instead of just default e-mail and password. Unfortunately all the guides/documentation I found so far are very confusing for someone who hasn’t used Firebase before and/or don’t relate to Android and Java development. I would really appreciate some advice as to what would be the best way to add some extra fields to my registration form and then store that data in Firebase.

    • JustForFun App

      Hey Jacek,

      You can store other information of user. You need to create a node called user and when ever user registers you need to create object of users which has all details like name, dob etc and push it to that node. Hope this helps.:)

      You can check this app called “The WordAme” it does in the same manner.
      https://play.google.com/store/apps/details?id=justforfun.com.wordame

  • Akanksh

    Im trying to build a notification app using firebase cloud messaging for my final year project. Can anybody help me with it??
    Thanks in advance

  • raghu teja

    Download option is not working…Please check..

    • Fixed. Pls check now.

      • raghu teja

        Yeah..Worked..Thank you..:)

  • Septian Adi Wijaya

    hi @ravi8x:disqus I faced the issue about token refreshed in firebase. When user login in different device with same user ID, token gonna refreshed to the new one device, and the older token gonna invalidated after 60minutes right?

    And if I want to give push notification after 60 minutes end. User with the newer token gonna get the notification, the user with older token is not going to get notification, right?

    My main question is. Is the firebase Auth can be handling about the issue I faced?
    Please give me some insight!

    • First question. Is firebase auth works on token based system?

      • Septian Adi Wijaya

        I don’t know, I have no idea about it. I still looking for reference for handling token to be used multi login in one account for push notif. May be you have any suggestion for me about the issue I facing?

  • Arteezy

    will this store details(registration) in database or only in auth section of firebase

  • Yusuf Charles

    Nice Post. I am trying to build an app where user registers and chooses a particular item (fruits or food). Based on the item he chooses, he is automatically paired with someone (another user) that chooses the same item he has chosen. Can anyone help out?. Please

  • Arun P M

    Hi..
    Cool post. Loved it!. Please share more knowledge like this.
    Thanks buddy .

  • binod lamichhane

    i am getting an error===== “cannnot find symbol variable toolbar”? how to handle this error?

    • Anangpal Singh Rathore (Nandsi

      I also have same error … all id on right place but it show error..
      if you solved it than tell me also please.

    • Jay Clarens

      i also have same error.

    • Tired

      dude jus choose to ignore all the error, im getting the same error as well.

  • Nurfarahin Natasya

    Hi. Its a great tutorial here. Helps me a lot. But i would like to ask, is there a possible way that I can retrieve user’s password from Firebase? Or create another input in Login page to differentiate the user category and store it into the firebase authentication?

  • saravana

    where the data are stored

    • Nandha kumar

      In The Firebase Console -> users Section.

  • Seul Mi

    SUCK, ITS LOADING TOO LONG :((

  • Pooja Ravi

    When i try to run the app,it shows firebase auth has stopped on my phone.Please help!

  • Ankita Indi

    @ravi8x:disqus sir can i add navigation drawer to this exisiting source code that i have downloaded

  • shashi patil

    working perfectly nice job ravi bro

  • Gor Arshakjan

    Can u help?? java.lang.RuntimeException: Unable to start activity ComponentInfo{.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method ‘void android.support.v7.app.ActionBar.setTitle(java.lang.CharSequence)’ on a null object reference

  • pammy

    Hi. Ravi. Great tutorial as always. Your tutorials are so easy to follow. I want to ask if I can extend this code to add firebase chat

  • Anangpal Singh Rathore (Nandsi

    Hello Ravi, I always follow you. I want to ask something to you.. hope you reply me..
    Q 1: where I put that ?: as you write above in post.Below are the quick code snippets to other user functionalities.
    1. #Checking User Session
    2. #Change Password
    3. #Change Email
    4. #Deleting Account / User
    5. #Sign Out
    Q 2: how I link this with Facebook and google plus login?

    Thanks in advance

  • Hai Master , I have Problem ..
    LogCat :

    FATAL EXCEPTION: main
    Process: deckydroid.login_firebase, PID: 8026
    java.lang.RuntimeException: Unable to start activity ComponentInfo{deckydroid.login_firebase/deckydroid.login_firebase.MainActivity}: java.lang.IllegalStateException: This Activity already has an action bar supplied by the window decor. Do not request Window.FEATURE_SUPPORT_ACTION_BAR and set windowActionBar to false in your theme to use a Toolbar instead.
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2318)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2396)
    at android.app.ActivityThread.access$800(ActivityThread.java:139)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1293)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:149)
    at android.app.ActivityThread.main(ActivityThread.java:5257)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:515)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:609)
    at dalvik.system.NativeStart.main(Native Method)
    Caused by: java.lang.IllegalStateException: This Activity already has an action bar supplied by the window decor. Do not request Window.FEATURE_SUPPORT_ACTION_BAR and set windowActionBar to false in your theme to use a Toolbar instead.
    at android.support.v7.app.AppCompatDelegateImplV9.setSupportActionBar(AppCompatDelegateImplV9.java:207)
    at android.support.v7.app.AppCompatActivity.setSupportActionBar(AppCompatActivity.java:130)
    at deckydroid.login_firebase.MainActivity.onCreate(MainActivity.java:36)
    at android.app.Activity.performCreate(Activity.java:5411)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2270)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2396)
    at android.app.ActivityThread.access$800(ActivityThread.java:139)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1293)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:149)
    at android.app.ActivityThread.main(ActivityThread.java:5257)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:515)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:609)
    at dalvik.system.NativeStart.main(Native Method)
    04-24 11:53:44.542 8026-8026/deckydroid.login_firebase I/Process: Sending signal. PID: 8026 SIG: 9

    Please Help Me

  • Mohan

    i’m facing the error com.google.firebase.database does not exist. help me to resolve this error

  • Cem

    Hey man, it’s a very nice tutorial thank you for that. I tried to compile the code and it works well but there is a problem when I login or register via emulator it just waits and does nothing. It doesn’t sent the data to firebase, There is a waiting symbol which is rotating, just rotating.. Why it’might be doing it?

    • Check the Logcat for errors.

      • Kalim Ahmad

        Plz bro kya aap music player activity bana sakte ho jo json se data collect krta ho? aur notification player aur minimize krte hi neeche aur activities py b player neeche rehta ho with art image? audio url se play krta ho?

  • Raymond Lau

    @ravi8x:disqus
    Hi, Well tutorial. Thank you so much. But i still have some problem and can’t fix it .
    I just copy the code you posted. with the xml have a error message : Render Problem
    Couldn’t resolve resource @id/visible
    Can you help me to fix this bug ?

  • Nilvandro Muianga

    Nice tutorial, it was so helpful to me.

  • Mohan

    sir I created the app by following your tutorial, when I run it in emulator signup activity works well but I click the forgot password or login button the application exits.

  • Sanchit Kalra

    I created the app but when I launch the app on device, the app doesn’t start and instead crashes. It says that the app has stopped. I followed the tutorial is given. Why is my app crashing and how can I fix this?

    • Check error log in android studio (Android Monitor).

      • Sanchit Kalra

        Saw that the ProgressBar was making issues. Commented that and now it works. Plan to implement Progress Dialog now. Anyways thanks. You have been a great help all this time. 🙂

  • Anuj Gajbhiye

    Ravi Tamada
    fatal exception bro!!
    Attempt
    to invoke virtual method ‘void
    android.support.v7.widget.Toolbar.setTitle(java.lang.CharSequence)’ on a
    null object reference

    help!!!!!!!

  • Anele

    Hi Ravi Tamada, the i am creating is repeatedly and cant start, https://uploads.disquscdn.com/images/9a86425c6df0881ba628e5e7aa6eaef77107197a98ba99473f8fc9d69f995c0f.png

    i have Checked error log in android studio (Android Monitor) and commented out the ProgressBar in all activities and it still doesnt want please let me know maybe where i went wrong

  • Thx Ravi, it works for me

  • Rushi Pawar

    does it verify users email???

  • Kaushal Topinkatti

    fantastic thank you

  • Ian Kush Maina

    Wassup Ravi. I have followed your tutorial and everything is working perfectly. Though i got an issue. When i register a user and go back to the Log in page, the Log in button is not working. In fact all buttons on the log in page stop working . What could be the problem?

  • Raoua Mahjbi

    nice

  • ibrahim

    I got error – Cannot resolve symbol ‘FirebaseAuth’.in all java files
    Help please.

    • naresh gaur

      compile ‘com.google.firebase:firebase-auth:11.0.0’

      put this in your gradel app file

  • Mohamed Zaid Farook

    Mr.Ravi if I want to display a hello message displaying the signed in user’s email address, i want to implement it in a different page how can I do it?

  • Vismay Patil

    signup.java

    package com.example.visma.medico;

    import android.content.Intent;
    import android.os.Bundle;
    import android.support.annotation.NonNull;
    import android.support.v7.app.AppCompatActivity;
    import android.text.TextUtils;
    import android.view.View;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.ProgressBar;
    import android.widget.TextView;
    import android.widget.Toast;

    import com.google.android.gms.tasks.OnCompleteListener;
    import com.google.android.gms.tasks.Task;
    import com.google.firebase.auth.AuthResult;
    import com.google.firebase.auth.FirebaseAuth;

    public class signup extends AppCompatActivity {

    EditText userName,emailId,password1;
    TextView signin;
    ProgressBar progressBar;
    FirebaseAuth auth;
    Button register;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.signup);
    auth = FirebaseAuth.getInstance();

    userName = (EditText) findViewById(R.id.userName);
    emailId = (EditText) findViewById(R.id.emailId);
    password1 = (EditText) findViewById(R.id.pasword1);
    signin = (TextView) findViewById(R.id.signin);
    signin.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
    finish();
    }
    });
    register = (Button) findViewById(R.id.register);
    register.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
    String uname =userName.getText().toString().trim();
    String mail = emailId.getText().toString().trim();
    String pass = password1.getText().toString().trim();

    if(TextUtils.isEmpty(uname)){
    Toast.makeText(getApplicationContext(),”Enter username!”, Toast.LENGTH_SHORT).show();
    return;
    }
    if(TextUtils.isEmpty(mail)){
    Toast.makeText(getApplicationContext(),”Enter email!”, Toast.LENGTH_SHORT).show();
    return;
    }
    if(TextUtils.isEmpty(pass)){
    Toast.makeText(getApplicationContext(),”Enter password!”, Toast.LENGTH_SHORT).show();
    return;
    }
    if(pass.length() < 6){
    Toast.makeText(getApplicationContext(), "Password too short, enter minimum 6 characters!",Toast.LENGTH_SHORT).show();
    return;
    }
    progressBar.setVisibility(View.VISIBLE);

    auth.createUserWithEmailAndPassword(mail,pass).addOnCompleteListener(signup.this, new OnCompleteListener() {
    @Override
    public void onComplete(@NonNull Task task) {
    Toast.makeText(signup.this, “createUserWithEmail:onComplete:” + task.isSuccessful(),Toast.LENGTH_SHORT).show();
    progressBar.setVisibility(View.GONE);
    if(!task.isSuccessful()){
    Toast.makeText(signup.this, “Authntication failed!” + task.getException(), Toast.LENGTH_SHORT).show();
    }
    else{
    startActivity(new Intent(signup.this, index.class));
    finish();
    }
    }
    });
    }
    });
    }
    protected void onResume() {

    super.onResume();
    progressBar.setVisibility(View.GONE);
    }
    }

    index.java

    package com.example.visma.medico;

    import android.os.Bundle;
    import android.support.v7.app.AppCompatActivity;
    import android.widget.TextView;

    public class index extends AppCompatActivity {
    TextView textview;
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.index);
    }
    }

    signup.xml

    index.xml

    manifest.xml

    Application is getting force closed, using usb debugging mode.

  • Ajay Wade

    Sir,awesome to talk you…
    thanks sir for the greatest tutorials….
    i got an one issue
    Question:- where to place this code given in screenshot? https://uploads.disquscdn.com/images/6402c6d972be072f3ee56869e72c36bd942abacff33fe30c0b01fbe43fbfaa83.png

  • Ajay Wade

    sorry,i found that where to keep these code….

  • Cesar David Leon Ramirez

    Hi my friend, I have a problem, in the Signup when i do click in the login button the app go directly to the last activity no to the login activity. You can help me please.

    package com.tvlosaltos.toolstecnicos;

    import android.content.Intent;
    import android.os.Bundle;
    import android.support.annotation.NonNull;
    import android.support.v7.app.AppCompatActivity;
    import android.text.TextUtils;
    import android.view.View;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.ProgressBar;
    import android.widget.Toast;

    import com.google.android.gms.tasks.OnCompleteListener;
    import com.google.android.gms.tasks.Task;
    import com.google.firebase.auth.AuthResult;
    import com.google.firebase.auth.FirebaseAuth;

    public class login extends AppCompatActivity {

    private EditText inputEmail, inputPassword;
    private FirebaseAuth auth;
    private ProgressBar progressBar;
    private Button btnSignup, btnLogin, btnReset;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    //Get Firebase auth instance
    auth = FirebaseAuth.getInstance();

    if (auth.getCurrentUser() != null) {
    startActivity(new Intent(login.this, escenarios.class));
    finish();
    }
    // set the view now
    setContentView(R.layout.activity_login);

    inputEmail = (EditText) findViewById(R.id.email);
    inputPassword = (EditText) findViewById(R.id.password);
    progressBar = (ProgressBar) findViewById(R.id.progressBar);
    btnSignup = (Button) findViewById(R.id.btn_signup);
    btnLogin = (Button) findViewById(R.id.btn_login);
    btnReset = (Button) findViewById(R.id.btn_reset_password);

    //Get Firebase auth instance
    auth = FirebaseAuth.getInstance();

    btnSignup.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
    startActivity(new Intent(login.this, escenarios.class));
    }
    });

    btnReset.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
    startActivity(new Intent(login.this, Reset_password.class));
    }
    });

    btnLogin.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
    String email = inputEmail.getText().toString();
    final String password = inputPassword.getText().toString();

    if (TextUtils.isEmpty(email)) {
    Toast.makeText(getApplicationContext(), “Enter email address!”, Toast.LENGTH_SHORT).show();
    return;
    }

    if (TextUtils.isEmpty(password)) {
    Toast.makeText(getApplicationContext(), “Enter password!”, Toast.LENGTH_SHORT).show();
    return;
    }

    progressBar.setVisibility(View.VISIBLE);

    //authenticate user
    auth.signInWithEmailAndPassword(email, password)
    .addOnCompleteListener(login.this, new OnCompleteListener() {
    @Override
    public void onComplete(@NonNull Task task) {
    // If sign in fails, display a message to the user. If sign in succeeds
    // the auth state listener will be notified and logic to handle the
    // signed in user can be handled in the listener.
    progressBar.setVisibility(View.GONE);
    if (!task.isSuccessful()) {
    // there was an error
    if (password.length() < 6) {
    inputPassword.setError(getString(R.string.minimum_password));
    } else {
    Toast.makeText(login.this, getString(R.string.auth_failed), Toast.LENGTH_LONG).show();
    }
    } else {
    Intent intent = new Intent(login.this, escenarios.class);
    startActivity(intent);
    finish();
    }
    }
    });
    }
    });
    }
    }

  • DV

    package com.example.com.sample;

    import android.content.Intent;
    import android.support.annotation.NonNull;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.support.v7.widget.Toolbar;
    import android.text.TextUtils;
    import android.view.View;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.ProgressBar;
    import android.widget.Toast;

    import com.google.android.gms.tasks.OnCompleteListener;
    import com.google.android.gms.tasks.Task;
    import com.google.firebase.auth.AuthResult;
    import com.google.firebase.auth.FirebaseAuth;

    public class LoginActivity extends AppCompatActivity {

    private EditText inputEmail, inputPassword;
    private FirebaseAuth auth;
    private ProgressBar progressBar;
    private Button btnSignup, btnLogin, btnReset;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    //Get Firebase auth instance
    auth = FirebaseAuth.getInstance();

    if (auth.getCurrentUser() != null) {
    startActivity(new Intent(LoginActivity.this, MainActivity.class));
    finish();
    }

    // set the view now
    setContentView(R.layout.activity_login);

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    inputEmail = (EditText) findViewById(R.id.email);
    inputPassword = (EditText) findViewById(R.id.password);
    progressBar = (ProgressBar) findViewById(R.id.progressBar);
    btnSignup = (Button) findViewById(R.id.btn_signup);
    btnLogin = (Button) findViewById(R.id.btn_login);
    btnReset = (Button) findViewById(R.id.btn_reset_password);

    //Get Firebase auth instance
    auth = FirebaseAuth.getInstance();

    btnSignup.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
    startActivity(new Intent(LoginActivity.this, SignUpActivity.class));
    }
    });

    btnReset.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
    startActivity(new Intent(LoginActivity.this, ResetPasswordActivity.class));
    }
    });

    btnLogin.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
    String email = inputEmail.getText().toString();
    final String password = inputPassword.getText().toString();

    if (TextUtils.isEmpty(email)) {
    Toast.makeText(getApplicationContext(), “Enter email address!”, Toast.LENGTH_SHORT).show();
    return;
    }

    if (TextUtils.isEmpty(password)) {
    Toast.makeText(getApplicationContext(), “Enter password!”, Toast.LENGTH_SHORT).show();
    return;
    }

    progressBar.setVisibility(View.VISIBLE);

    //authenticate user
    auth.signInWithEmailAndPassword(email, password)
    .addOnCompleteListener(LoginActivity.this, new OnCompleteListener() {
    @Override
    public void onComplete(@NonNull Task task) {
    // If sign in fails, display a message to the user. If sign in succeeds
    // the auth state listener will be notified and logic to handle the
    // signed in user can be handled in the listener.
    progressBar.setVisibility(View.GONE);
    if (!task.isSuccessful()) {
    // there was an error
    if (password.length() < 6) {
    inputPassword.setError(getString(R.string.minimum_password));
    } else {
    Toast.makeText(LoginActivity.this, getString(R.string.auth_failed), Toast.LENGTH_LONG).show();
    }
    } else {
    Intent intent = new Intent(LoginActivity.this, MainActivity.class);
    startActivity(intent);
    finish();
    }
    }
    });
    }
    });
    }}

  • DV

    Process: com.example.com.sample, PID: 8082
    java.lang.NullPointerException: Attempt to invoke virtual method ‘java.lang.Class java.lang.Object.getClass()’ on a null object reference
    at android.support.v4.app.BackStackRecord.doAddOp(BackStackRecord.java:380)
    at android.support.v4.app.BackStackRecord.add(BackStackRecord.java:375)
    at android.support.v4.app.FragmentPagerAdapter.instantiateItem(FragmentPagerAdapter.java:103)
    at android.support.v4.view.ViewPager.addNewItem(ViewPager.java:1034)
    at android.support.v4.view.ViewPager.populate(ViewPager.java:1248)
    at android.support.v4.view.ViewPager.populate(ViewPager.java:1116)
    at android.support.v4.view.ViewPager$3.run(ViewPager.java:273)
    at android.view.Choreographer$CallbackRecord.run(Choreographer.java:871)
    at android.view.Choreographer.doCallbacks(Choreographer.java:683)
    at android.view.Choreographer.doFrame(Choreographer.java:616)
    at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:857)
    at android.os.Handler.handleCallback(Handler.java:751)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.os.Looper.loop(Looper.java:154)
    at android.app.ActivityThread.main(ActivityThread.java:6077)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)

  • Eliott Balmin

    Hi, can i use modified code from this tutorial in an app that is meant to be published?

  • Tham

    Hi, I’m stucked at the LoginActivity.java part, when I compile it, the (Error:(41, 54) error: cannot find symbol variable toolbar) showed, it highlights all the r.id, if I delete Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); , the code can be compile without error but when you install it on your phone it will crashed. How to fix this? Thank you.

    • Tham

      TO ANY 1 still LOOKING at this tutorial, DO NOT USE THE CODE ABOVE!!!!!! You can use it to understand the procedure but please do not copy n paste it, just download the complete code and change to whatever you want it to be. The code above is fullfilled with ton of errors if you copy and paste it because it is different with the code he used as in the downloaded code.

  • ibrahim

    Thanks. How to add other field like username to registration form??

  • stuart little
    • Shivam Goyal

      you have to register your app on firebase.

  • Ridham Dave

    I am not getting the progress bar!

  • ahmad zainul

    hi Ravi, why my login session always stopped working when i clicked it, is there right code for LoginActivity, same with MainActivity?, please reply soon

    • Julian Parker

      Inside of the signup activity you need to create an Intent.

      startActivity(new Intent(SignUpActivty.this, LoginActivity.class));

      • Bhavik Mehta

        nope that is not the solution. what if there are multiple users? i am having one issue.
        if i am clicking on “already registered. login me” . it does take me to login screen, but does not show anything. (in short i am not able to go to login screen anyhow).

  • rachana

    i am getting these errors while executing the program.can u please explain?

    Information:Gradle tasks [:app:generateDebugSources, :app:mockableAndroidJar, :app:prepareDebugUnitTestDependencies, :app:generateDebugAndroidTestSources]
    C:UsersrachanakavvaAndroidStudioProjectsdemoappappsrcmainreslayoutactivity_main.xml
    Error:(13, 24) No resource found that matches the given name (at ‘theme’ with value ‘@style/AppTheme.AppBarOverlay’).
    Error:(22, 29) No resource found that matches the given name (at ‘popupTheme’ with value ‘@style/AppTheme.PopupOverlay’).
    C:UsersrachanakavvaAndroidStudioProjectsdemoappappsrcmainreslayoutactivity_reset_password.xml
    Error:(92) Error parsing XML: not well-formed (invalid token)
    C:UsersrachanakavvaAndroidStudioProjectsdemoappappbuildintermediatesresmergeddebuglayoutactivity_main.xml
    Error:(13, 24) No resource found that matches the given name (at ‘theme’ with value ‘@style/AppTheme.AppBarOverlay’).
    Error:(22, 29) No resource found that matches the given name (at ‘popupTheme’ with value ‘@style/AppTheme.PopupOverlay’).
    C:UsersrachanakavvaAndroidStudioProjectsdemoappappbuildintermediatesresmergeddebuglayoutactivity_reset_password.xml
    Error:(92) Error parsing XML: not well-formed (invalid token)
    Error:Execution failed for task ‘:app:processDebugResources’.
    > com.android.ide.common.process.ProcessException: Failed to execute aapt
    Information:BUILD FAILED
    Information:Total time: 3.859 secs
    Information:7 errors
    Information:0 warnings
    Information:See complete output in console

    • saksham sneh

      me too…

    • Tri Raditya Inawityanto

      me too…. dear admin… can u help ?

    • Bhavik Mehta

      hey rachna, maybe you need to check your styles.xml file(in res/values) directory. and if required you need change to this.


      @color/colorPrimary
      @color/colorPrimaryDark
      @color/colorAccent

  • Pankaj Saxena

    how to get all email id in my application which is registered on fcm.

  • Arijit Roy

    Hey Ravi, thanks for this awesome tutorial. Can you also add a tutorial for phone verification using firebase as a part of registration.

    -AR

    • What do you mean by Phone Verification?

      • Arijit Roy

        firebase also provides SMS otp verification as a part of auth (Phone Auth).

  • dinu lal