ZOFTINO.COM android and web dev tutorials

Android Firebase Email Password Authentication

Firebase makes it easy to develop an android app using services offered by Firebase. To provide data security and personalized experience to user, you need to authenticate and identify the user. Using firebase authentication, you can secure the data and protect it from unauthorized access to it.

In this article, I am going to show how to perform email password authentication including adding a user to Firebase, authenticating registered user, updating password, requesting reset password email and verifying email and to secure Firestore database data using Firebase email password authentication and security rules.

Table of Contents

Android Firebase Authentication Setup

Below are the steps to setup Firestore authentication.

  • Login to Firebase console.
  • Add project to Firebase by clicking add project link on main screen of Firebase console.
  • To enable email and password authentication in Firebase console, click target project, then go to authentication, click sign-in method tab, enable email/password and save change.android firebase authentication setup
  • If any of Firebase services is not used in your android app project, you’ll have to install Firebase SDK. To install Firebase SDK, go to project overview section in Firebase console, click add-Firebase to android project and follow steps to generate google-services.json. Download the file and save it in your project under app folder.
  • Add below entry to bottom of app level gradle build file.
    plugin: 'com.google.gms.google-services'
  • Add below entry to project level gradle build file in dependencies element.
    classpath 'com.google.gms:google-services:3.1.0'
  • Add Firebase authentication library to app level build file. Since we are going to use Firestore to show how to allow authenticated user to read and write only his/her data, we will add Firestore library to project.
    implementation 'com.google.firebase:firebase-firestore:11.6.0'
    implementation 'com.google.firebase:firebase-auth:11.6.0'

Email Password Firebase Authentication Registration

To enable user to enter email and password for creating account, screen containing text and password fields will be shown to user. On submitting email address and password, basic data validation is done to check for empty values.

To check whether the email id exists in firebase or not, fetchProvidersForEmail method is called on FirebaseAuth object passing email address. In the OnCompleteListener’s complete method, you can get ProviderQueryResult object and find out if email address is already used or not by checking providers list size. If your app allows different authentication mechanisms, you need to handle this scenario differently.

android firebase email password authentication, registration and login example
private void performLoginOrAccountCreation(final String email, final String password){
    firebaseAuth.fetchProvidersForEmail(email).addOnCompleteListener(
            this, new OnCompleteListener<ProviderQueryResult>() {
                @Override
                public void onComplete(@NonNull Task<ProviderQueryResult> task) {
                    if (task.isSuccessful()) {
                        Log.d(TAG, "checking to see if user exists in firebase or not");
                        ProviderQueryResult result = task.getResult();

                        if(result != null && result.getProviders()!= null
                                && result.getProviders().size() > 0){
                            Log.d(TAG, "User exists, trying to login using entered credentials");
                            performLogin(email, password);
                        }else{
                            Log.d(TAG, "User doesn't exist, creating account");
                            registerAccount(email, password);
                        }
                    } else {
                        Log.w(TAG, "User check failed", task.getException());
                        Toast.makeText(EmailPasswordAuthActivity.this,
                                "There is a problem, please try again later.",
                                Toast.LENGTH_SHORT).show();

                    }
                    //hide progress dialog
                    hideProgressDialog();
                    //enable and disable login, logout buttons depending on signin status
                    showAppropriateOptions();
                }
            });
}

If email id doesn’t exist, then we can proceed with creating account by calling createUserWithEmailAndPassword method on FirebaseAuth object passing email and password. In the listener, you can know the registration status and display appropriate message to user.

private void registerAccount(String email, String password) {
    firebaseAuth.createUserWithEmailAndPassword(email, password)
            .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                    if (task.isSuccessful()) {
                        Log.d(TAG, "account created");
                    } else {
                        Log.d(TAG, "register account failed", task.getException());
                        Toast.makeText(EmailPasswordAuthActivity.this,
                                "account registration failed.",
                                Toast.LENGTH_SHORT).show();
                    }
                    //hide progress dialog
                    hideProgressDialog();
                    //enable and disable login, logout buttons depending on signin status
                    showAppropriateOptions();
                }
            });
}

Email Password Firebase Authentication Login

If email id exists in Firebase, then we can proceed with sing-in by calling signInWithEmailAndPassword method on FirebaseAuth object passing email and password. In the listener, you can know the login status and display message to user.

After successful login, registration or login fields will be made invisible and sing out, update password, verify email and functionality access buttons will be made visible so that user can perform profile related actions or access app functionality that is available for authenticated users.

android firebase email password authentication, logout, update password, accessing secure data example
 private void performLogin(String email, String password) {
    firebaseAuth.signInWithEmailAndPassword(email, password)
            .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                    if (task.isSuccessful()) {
                        Log.d(TAG, "login success");
                    } else {
                        Log.e(TAG, "Login fail", task.getException());
                        Toast.makeText(EmailPasswordAuthActivity.this,
                                "Authentication failed.",
                                Toast.LENGTH_SHORT).show();
                    }
                    //hide progress dialog
                    hideProgressDialog();
                    //enable and disable login, logout buttons depending on signin status
                    showAppropriateOptions();
                }
            });
}
 

Firebase Authentication Update Password

You can provide update password functionality to authenticated user. To update password in Firebase, you need to call updatePassword method on FirebaseAuth object passing new password as shown below.

 private void updatePassword() {

    final FirebaseUser user = firebaseAuth.getCurrentUser();
    final String newPwd = ((EditText) findViewById(R.id.update_password_t)).getText().toString();
    if(!validateResetPassword(newPwd)){
        Toast.makeText(EmailPasswordAuthActivity.this,
                "Invalid password, please enter valid password",
                Toast.LENGTH_SHORT).show();
        return;
    }
    user.updatePassword(newPwd)
            .addOnCompleteListener(new OnCompleteListener<Void>() {
                @Override
                public void onComplete(@NonNull Task<Void> task) {
                    if (task.isSuccessful()) {
                        Toast.makeText(EmailPasswordAuthActivity.this,
                                "Password has been updated",
                                Toast.LENGTH_SHORT).show();
                    } else {
                        Log.e(TAG, "Error in updating passowrd",
                                task.getException());
                        Toast.makeText(EmailPasswordAuthActivity.this,
                                "Failed to update passwrod.",
                                Toast.LENGTH_SHORT).show();
                    }
                }
            });
}
 

Firebase Authentication Verify Email

To verify email address used for creating email-password authentication account, an email with a link can be sent to user by calling sendEmailVerification method on FirebaseAuth object.

Firebase Authentication Reset Password

To provide reset password option for non authenticated users, you can prompt user to enter email and call sendPasswordResetEmail on FirebaseAuth object to send an email containing link that allows user to reset password. Authentication email templates can be customized in firebase console.

android firebase authentication custom templates
 private void sendResetPasswordEmail() {
    final String email = ((EditText) findViewById(R.id.reset_password_email))
            .getText().toString();
    firebaseAuth.sendPasswordResetEmail(email)
            .addOnCompleteListener(this, new OnCompleteListener<Void>() {
                @Override
                public void onComplete(@NonNull Task<Void> task) {

                    if (task.isSuccessful()) {
                        Toast.makeText(EmailPasswordAuthActivity.this,
                                "Reset password code has been emailed to "
                                        + email,
                                Toast.LENGTH_SHORT).show();
                    } else {
                        Log.e(TAG, "Error in sending reset password code",
                                task.getException());
                        Toast.makeText(EmailPasswordAuthActivity.this,
                                "There is a problem with reset password, try later.",
                                Toast.LENGTH_SHORT).show();
                    }
                }
            });
}
 

Restricting App Functionality to Authenticated Users

If there are activities which can be accessed only by authenticated users, you need to first check whether user is authenticated user or not. If user is not authenticated, send the user to login activity. The right lifecycle callback method in activity to keep the check is onCreate method.

In case of Firebase authentication, you find out whether user is singed in or not by calling getCurrentUser method on FirebaseAuth object and using resulting FirebaseUser object.

 user = FirebaseAuth.getInstance().getCurrentUser();
if(user == null){
    //if user is not authenticated show authentication screen
    Intent i = new Intent();
    i.setClass(this, EmailPasswordAuthActivity.class);
    startActivity(i);
}
 

Securing Firestore Data

You can secure Firestore data using security rules and Firebase authentication. To give read and write access to firestore data that belongs to a user, first user needs to be authenticated, then user id needs to be added to documents while documents are added to firestore and finally define security rules for Firestore in firebase console.

Securing Firestore Data Example

You can learn how to secure Firebase data using order entry example.

android firebase authentication and firestore data security with security rules example

Firestore Security rules

service cloud.firestore {
  match /databases/{database}/documents {
  	match /orders/{uid} {
      allow read, write: if request.auth.uid == uid;
    }
    match /{document=**} {
      allow read, write: if true;
    }
  }
}

Firebase Authentication Activity

public class EmailPasswordAuthActivity extends AppCompatActivity {

    private static final String TAG = "EmailPasswordAuth";

    private EditText emailET;
    private EditText passwordET;


    private FirebaseAuth firebaseAuth;

    @VisibleForTesting
    public ProgressDialog progressDialog;

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

        Toolbar tb = findViewById(R.id.toolbar);
        setSupportActionBar(tb);
        tb.setSubtitle("Authentication");

        emailET = findViewById(R.id.email);
        passwordET = findViewById(R.id.password);

        firebaseAuth = FirebaseAuth.getInstance();

        setButtonListeners();
    }
    private void setButtonListeners(){
        //login button
        findViewById(R.id.login_b).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                handleRegistrationLogin();
            }
        });
        //reset password - for unauthenticated user
        findViewById(R.id.rest_password_b).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                sendResetPasswordEmail();
            }
        });

        //logout button
        findViewById(R.id.logout_b).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                logOut();
            }
        });

        //Verify email button
        findViewById(R.id.verify_b).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                sendEmailVerificationMsg();
            }
        });

        //update password - for signed in user
        findViewById(R.id.update_password_b).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                updatePassword();
            }
        });

        //Order functionality to show how to secure firestore data
        //using firebase authentication and firestore security rules
        findViewById(R.id.order_b).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent i = new Intent();
                i.setClass(EmailPasswordAuthActivity.this, OrderActivity.class);
                startActivity(i);
            }
        });
    }
    @Override
    public void onStart() {
        super.onStart();
        showAppropriateOptions();
    }
    private void  handleRegistrationLogin(){
        final String email = emailET.getText().toString();
        final String password = passwordET.getText().toString();

        if (!validateEmailPass(email, password)) {
            return;
        }

        //show progress dialog
        showProgressDialog();

        //perform login and account creation depending on existence of email in firebase
        performLoginOrAccountCreation(email, password);
    }
    private void performLoginOrAccountCreation(final String email, final String password){
        firebaseAuth.fetchProvidersForEmail(email).addOnCompleteListener(
                this, new OnCompleteListener<ProviderQueryResult>() {
                    @Override
                    public void onComplete(@NonNull Task<ProviderQueryResult> task) {
                        if (task.isSuccessful()) {
                            Log.d(TAG, "checking to see if user exists in firebase or not");
                            ProviderQueryResult result = task.getResult();

                            if(result != null && result.getProviders()!= null
                                    && result.getProviders().size() > 0){
                                Log.d(TAG, "User exists, trying to login using entered credentials");
                                performLogin(email, password);
                            }else{
                                Log.d(TAG, "User doesn't exist, creating account");
                                registerAccount(email, password);
                            }
                        } else {
                            Log.w(TAG, "User check failed", task.getException());
                            Toast.makeText(EmailPasswordAuthActivity.this,
                                    "There is a problem, please try again later.",
                                    Toast.LENGTH_SHORT).show();

                        }
                        //hide progress dialog
                        hideProgressDialog();
                        //enable and disable login, logout buttons depending on signin status
                        showAppropriateOptions();
                    }
                });
    }
    private void performLogin(String email, String password) {
        firebaseAuth.signInWithEmailAndPassword(email, password)
                .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        if (task.isSuccessful()) {
                            Log.d(TAG, "login success");
                        } else {
                            Log.e(TAG, "Login fail", task.getException());
                            Toast.makeText(EmailPasswordAuthActivity.this,
                                    "Authentication failed.",
                                    Toast.LENGTH_SHORT).show();
                        }
                        //hide progress dialog
                        hideProgressDialog();
                        //enable and disable login, logout buttons depending on signin status
                        showAppropriateOptions();
                    }
                });
    }
    private void registerAccount(String email, String password) {
        firebaseAuth.createUserWithEmailAndPassword(email, password)
                .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        if (task.isSuccessful()) {
                            Log.d(TAG, "account created");
                        } else {
                            Log.d(TAG, "register account failed", task.getException());
                            Toast.makeText(EmailPasswordAuthActivity.this,
                                    "account registration failed.",
                                    Toast.LENGTH_SHORT).show();
                        }
                        //hide progress dialog
                        hideProgressDialog();
                        //enable and disable login, logout buttons depending on signin status
                        showAppropriateOptions();
                    }
                });
    }
    private boolean validateEmailPass(String email , String password) {
        boolean valid = true;

        if (TextUtils.isEmpty(email)) {
            emailET.setError("Required.");
            valid = false;
        }else if(!email.contains("@")){
            emailET.setError("Not an email id.");
            valid = false;
        } else{
            emailET.setError(null);
        }

        if (TextUtils.isEmpty(password)) {
            passwordET.setError("Required.");
            valid = false;
        }else if(password.length() < 6){
            passwordET.setError("Min 6 chars.");
            valid = false;
        }else {
            passwordET.setError(null);
        }

        return valid;
    }
    private boolean validateResetPassword(String password) {
        boolean valid = true;
        if (TextUtils.isEmpty(password) || password.length() < 6) {
            valid = false;
        }
        return valid;
    }
    public void showProgressDialog() {
        if (progressDialog == null) {
            progressDialog = new ProgressDialog(this);
            progressDialog.setMessage("Please wait!");
            progressDialog.setIndeterminate(true);
        }
        progressDialog.show();
    }

    public void hideProgressDialog() {
        if (progressDialog != null && progressDialog.isShowing()) {
            progressDialog.dismiss();
        }
    }
    private void showAppropriateOptions(){
        hideProgressDialog();
        FirebaseUser user = firebaseAuth.getCurrentUser();
        if (user != null) {
            findViewById(R.id.login_items).setVisibility(View.GONE);
            findViewById(R.id.logout_items).setVisibility(View.VISIBLE);

            findViewById(R.id.verify_b).setEnabled(!user.isEmailVerified());
        } else {
            findViewById(R.id.login_items).setVisibility(View.VISIBLE);
            findViewById(R.id.logout_items).setVisibility(View.GONE);
        }
    }

    private void sendEmailVerificationMsg() {
        findViewById(R.id.verify_b).setEnabled(false);

        final FirebaseUser user = firebaseAuth.getCurrentUser();
        user.sendEmailVerification()
                .addOnCompleteListener(this, new OnCompleteListener<Void>() {
                    @Override
                    public void onComplete(@NonNull Task<Void> task) {
                        findViewById(R.id.verify_b).setEnabled(true);
                        if (task.isSuccessful()) {
                            Toast.makeText(EmailPasswordAuthActivity.this,
                                    "Verification email has been sent to " + user.getEmail(),
                                    Toast.LENGTH_SHORT).show();
                        } else {
                            Log.e(TAG, "Error in sending verification email",
                                    task.getException());
                            Toast.makeText(EmailPasswordAuthActivity.this,
                                    "Failed to send verification email.",
                                    Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }
    //non-singed in user reset password email
    private void sendResetPasswordEmail() {
        final String email = ((EditText) findViewById(R.id.reset_password_email))
                .getText().toString();
        firebaseAuth.sendPasswordResetEmail(email)
                .addOnCompleteListener(this, new OnCompleteListener<Void>() {
                    @Override
                    public void onComplete(@NonNull Task<Void> task) {

                        if (task.isSuccessful()) {
                            Toast.makeText(EmailPasswordAuthActivity.this,
                                    "Reset password code has been emailed to "
                                            + email,
                                    Toast.LENGTH_SHORT).show();
                        } else {
                            Log.e(TAG, "Error in sending reset password code",
                                    task.getException());
                            Toast.makeText(EmailPasswordAuthActivity.this,
                                    "There is a problem with reset password, try later.",
                                    Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }

    private void updatePassword() {

        final FirebaseUser user = firebaseAuth.getCurrentUser();
        final String newPwd = ((EditText) findViewById(R.id.update_password_t)).getText().toString();
        if(!validateResetPassword(newPwd)){
            Toast.makeText(EmailPasswordAuthActivity.this,
                    "Invalid password, please enter valid password",
                    Toast.LENGTH_SHORT).show();
            return;
        }
        user.updatePassword(newPwd)
                .addOnCompleteListener(new OnCompleteListener<Void>() {
                    @Override
                    public void onComplete(@NonNull Task<Void> task) {
                        if (task.isSuccessful()) {
                            Toast.makeText(EmailPasswordAuthActivity.this,
                                    "Password has been updated",
                                    Toast.LENGTH_SHORT).show();
                        } else {
                            Log.e(TAG, "Error in updating passowrd",
                                    task.getException());
                            Toast.makeText(EmailPasswordAuthActivity.this,
                                    "Failed to update passwrod.",
                                    Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }
    private void logOut() {
        firebaseAuth.signOut();
        showAppropriateOptions();
    }
    @Override
    public void onStop() {
        super.onStop();
        hideProgressDialog();
    }

}

Authentication Activity

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".EmailPasswordAuthActivity">
    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary" />
    <android.support.constraint.ConstraintLayout
        android:id="@+id/login_items"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <TextView
            android:id="@+id/auth_tv"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="8dp"
            android:layout_marginRight="8dp"
            android:layout_marginTop="16dp"
            android:text="Authentication"
            android:textAppearance="@style/TextAppearance.AppCompat.Large"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

        <android.support.design.widget.TextInputLayout
            android:id="@+id/email_l"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="8dp"
            android:layout_marginRight="8dp"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/auth_tv">

            <EditText
                android:id="@+id/email"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="Email address" />
        </android.support.design.widget.TextInputLayout>

        <android.support.design.widget.TextInputLayout
            android:id="@+id/password_l"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="8dp"
            android:layout_marginRight="8dp"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/email_l">

            <EditText
                android:id="@+id/password"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="Password"
                android:inputType="textWebPassword" />
        </android.support.design.widget.TextInputLayout>

        <Button
            android:id="@+id/login_b"
            style="@style/Widget.AppCompat.Button.Colored"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="8dp"
            android:layout_marginRight="8dp"
            android:layout_marginTop="16dp"
            android:text="Register/Login"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/password_l" />
        <EditText
            android:id="@+id/reset_password_email"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="8dp"
            android:layout_marginRight="8dp"
            android:layout_marginTop="32dp"
            android:hint="Enter eamil id"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/login_b" />

        <Button
            android:id="@+id/rest_password_b"
            style="@style/Widget.AppCompat.Button.Colored"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="8dp"
            android:layout_marginRight="8dp"
            android:text="Reset Password"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/reset_password_email" />
    </android.support.constraint.ConstraintLayout>

    <android.support.constraint.ConstraintLayout
        android:id="@+id/logout_items"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <Button
            android:id="@+id/logout_b"
            style="@style/Widget.AppCompat.Button.Colored"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="8dp"
            android:layout_marginRight="8dp"
            android:layout_marginTop="16dp"
            android:text="Logout"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

        <Button
            android:id="@+id/verify_b"
            style="@style/Widget.AppCompat.Button.Colored"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="8dp"
            android:layout_marginRight="8dp"
            android:text="Verify Email"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/logout_b" />

        <EditText
            android:id="@+id/update_password_t"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="8dp"
            android:layout_marginRight="8dp"
            android:layout_marginTop="16dp"
            android:hint="Enter new password"
            android:inputType="textWebPassword"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/verify_b" />

        <Button
            android:id="@+id/update_password_b"
            style="@style/Widget.AppCompat.Button.Colored"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="8dp"
            android:layout_marginRight="8dp"
            android:text="Update Password"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/update_password_t" />
        <Button
            android:id="@+id/order_b"
            style="@style/Widget.AppCompat.Button.Colored"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="8dp"
            android:layout_marginRight="8dp"
            android:layout_marginTop="16dp"
            android:text="Orders Screen"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/update_password_b" />
    </android.support.constraint.ConstraintLayout>

</LinearLayout>

Order Activity

public class OrderActivity extends AppCompatActivity {

    private FirebaseUser user;
    private FirebaseFirestore firestoreDB;

    private RecyclerView orderList;

    private static final String TAG = "OrderActivity";

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

        user = FirebaseAuth.getInstance().getCurrentUser();
        if(user == null){
            //if user is not authenticated show authentication screen
            Intent i = new Intent();
            i.setClass(this, EmailPasswordAuthActivity.class);
            startActivity(i);
        }

        Toolbar tb = findViewById(R.id.toolbar);
        setSupportActionBar(tb);
        tb.setSubtitle("Firestore with authentication");

        orderList = (RecyclerView) findViewById(R.id.order_lst);
        LinearLayoutManager recyclerLayoutManager =
                new LinearLayoutManager(this.getApplicationContext());
        orderList.setLayoutManager(recyclerLayoutManager);
        DividerItemDecoration dividerItemDecoration =
                new DividerItemDecoration(orderList.getContext(),
                        recyclerLayoutManager.getOrientation());
        orderList.addItemDecoration(dividerItemDecoration);

        firestoreDB = FirebaseFirestore.getInstance();
        //display user orders in recycler view
        getOrders(user.getUid());

        findViewById(R.id.add_order).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                addOrderToFirestore();
            }
        });
    }
    private void getOrders(String userId) {
        firestoreDB.collection("orders")
                .whereEqualTo("uid", user.getUid())
                .get()
                .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
                    @Override
                    public void onComplete(@NonNull Task<QuerySnapshot> task) {
                        if (task.isSuccessful()) {
                            List<Order> orders = task.getResult().toObjects(Order.class);
                            OrdersRecyclerViewAdapter recyclerViewAdapter = new
                                    OrdersRecyclerViewAdapter(orders,
                                    OrderActivity.this);
                            orderList.setAdapter(recyclerViewAdapter);

                        } else {
                            Log.d(TAG, "Error getting documents: ", task.getException());
                        }
                    }
                });
    }
    private void addOrderToFirestore(){
        Order order = createOrderObj();
        firestoreDB.collection("orders")
                .add(order)
                .addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
                    @Override
                    public void onSuccess(DocumentReference documentReference) {
                        Log.d(TAG, "Order added - id: "
                                + documentReference.getId());
                        restData();
                        Toast.makeText(OrderActivity.this,
                                "Order has been added",
                                Toast.LENGTH_SHORT).show();
                    }
                })
                .addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        Log.w(TAG, "Error adding order", e);
                        Toast.makeText(OrderActivity.this,
                                "Order could not be added",
                                Toast.LENGTH_SHORT).show();
                    }
                });
    }
    private Order createOrderObj(){
        final Order order = new Order();
        order.setName(((TextView)findViewById(R.id.name_a)).getText().toString());
        order.setAmt(((TextView)findViewById(R.id.amount_a)).getText().toString());

        order.setUid(user.getUid());
        return order;
    }
    private void restData(){
        ((TextView)findViewById(R.id.name_a)).setText("");
        ((TextView)findViewById(R.id.amount_a)).setText("");
    }
}

Order Activity Layout

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    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"
    tools:context=".OrderActivity">
    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
    <TextView
        android:id="@+id/add_tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:text="Add Order"
        android:textAppearance="@style/TextAppearance.AppCompat.Large"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/toolbar"  />
    <android.support.design.widget.TextInputLayout
        android:id="@+id/item_name_la"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/add_tv">
        <EditText
            android:id="@+id/name_a"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Item name"/>
    </android.support.design.widget.TextInputLayout>
    <android.support.design.widget.TextInputLayout
        android:id="@+id/amount_la"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/item_name_la">
        <EditText
            android:id="@+id/amount_a"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Event type"/>
    </android.support.design.widget.TextInputLayout>
    <Button
        android:id="@+id/add_order"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        style="@style/Widget.AppCompat.Button.Colored"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/amount_la"
        android:text="Add Order"/>
    <TextView
        android:id="@+id/view_tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:text="Orders"
        android:textAppearance="@style/TextAppearance.AppCompat.Headline"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/add_order" />
    <android.support.v7.widget.RecyclerView
        android:id="@+id/order_lst"
        android:scrollbars="vertical"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/view_tv"/>
</android.support.constraint.ConstraintLayout>

RecyclerView Adapter

public class OrdersRecyclerViewAdapter extends
        RecyclerView.Adapter<OrdersRecyclerViewAdapter.ViewHolder> {

    private List<Order> orderList;
    private Context context;

    public OrdersRecyclerViewAdapter(List<Order> list, Context ctx) {
        orderList = list;
        context = ctx;
    }
    @Override
    public int getItemCount() {
        return orderList.size();
    }

    @Override
    public OrdersRecyclerViewAdapter.ViewHolder
    onCreateViewHolder(ViewGroup parent, int viewType) {

        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.order_item, parent, false);

        OrdersRecyclerViewAdapter.ViewHolder viewHolder =
                new OrdersRecyclerViewAdapter.ViewHolder(view);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(OrdersRecyclerViewAdapter.ViewHolder holder, int position) {
        final int itemPos = position;
        final Order order = orderList.get(position);
        holder.name.setText(order.getName());
        holder.amt.setText(order.getAmt());
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        public TextView name;
        public TextView amt;

        public ViewHolder(View view) {
            super(view);
            name = (TextView) view.findViewById(R.id.item_name);
            amt = (TextView) view.findViewById(R.id.item_amt);
        }
    }
}