Saving and Retrieving Data from Firebase Android Part one

In the last tutorial, I described how to sign up and sign in the user at Firebase. In this tutorial, I am going to describe how to save and retrieve the data at Firebase using Android.

If you are not Aware of Firebase Please refer here

if you want to learn about sign up and sign in users At Firebase refer my last tutorial here

So, Let’s Start:-

  1. Create an Activity to sign up and sign in the user.
  2. Create an Activity to save the user details at Firebase.
  3. Create an Activity to retrieve the data from Firebase and show in ListView.

Note: Please follow here to get JSON file and copy at Module’s root path and add the dependency and plugin.

Add the following dependencies to your module build.gradle

compile 'com.google.firebase:firebase-auth:9.0.0'
compile 'com.google.firebase:firebase-database:9.0.0'

create a layout to signup and sign the user.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
   >

    <LinearLayout
        android:id="@+id/layout_email_password"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:orientation="vertical">

        <EditText
            android:id="@+id/field_email"
            android:layout_width="250dp"
            android:layout_height="wrap_content"
            android:ellipsize="end"
            android:gravity="center_horizontal"
            android:hint="Enter your mail"
            android:inputType="textEmailAddress"
            android:maxLines="1" />

        <EditText
            android:id="@+id/field_password"
            android:layout_width="250dp"
            android:layout_height="wrap_content"
            android:ellipsize="end"
            android:gravity="center_horizontal"
            android:hint="Enter your password"
            android:inputType="textPassword"
            android:maxLines="1" />

    </LinearLayout>

    <LinearLayout
        android:id="@+id/layout_buttons"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/layout_email_password"
        android:layout_centerHorizontal="true"
        android:orientation="horizontal">

        <Button
            android:id="@+id/button_sign_in"
            android:layout_width="150dp"
            android:layout_height="wrap_content"
            android:text="Sign In" />


        <Button
            android:id="@+id/button_sign_up"
            android:layout_width="150dp"
            android:layout_height="wrap_content"
            android:text="Sign Up" />

    </LinearLayout>


</RelativeLayout>

MainActivity.java for User sign up, sign in and check if the user already signed in then show DashboardActivty.

package com.coderzpassion.firebasesample;

import android.app.ProgressDialog;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
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;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{

    private DatabaseReference mDatabase;
    private FirebaseAuth mAuth;

    private EditText mEmailField;
    private EditText mPasswordField;
    private Button mSignInButton;
    private Button mSignUpButton;

    private ProgressDialog mProgressDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mDatabase = FirebaseDatabase.getInstance().getReference();
        mAuth = FirebaseAuth.getInstance();

        // Views
        mEmailField = (EditText) findViewById(R.id.field_email);
        mPasswordField = (EditText) findViewById(R.id.field_password);
        mSignInButton = (Button) findViewById(R.id.button_sign_in);
        mSignUpButton = (Button) findViewById(R.id.button_sign_up);

        // Click listeners
        mSignInButton.setOnClickListener(this);
        mSignUpButton.setOnClickListener(this);

        // check if user is signed in then start dashboardactivity
        if(mAuth.getCurrentUser()!=null)
        {
            Intent intent=new Intent(MainActivity.this,DashBoardActivity.class);
            startActivity(intent);
            finish();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.button_sign_in:
                signIn();
                break;
            case R.id.button_sign_up:
                signUp();
                break;
        }

    }
    
    // to validate the form is user has filled the required fields
    private boolean validateForm() {
        boolean result = true;
        if (TextUtils.isEmpty(mEmailField.getText().toString())) {
            mEmailField.setError("Required");
            result = false;
        } else {
            mEmailField.setError(null);
        }

        if (TextUtils.isEmpty(mPasswordField.getText().toString())) {
            mPasswordField.setError("Required");
            result = false;
        } else {
            mPasswordField.setError(null);
        }

        return result;
    }

    private void signIn() {
        Log.d("MainActivity", "signIn");
        if (!validateForm()) {
            return;
        }

        showProgressDialog();
        String email = mEmailField.getText().toString();
        String password = mPasswordField.getText().toString();
// to sign in the user at firebase
        mAuth.signInWithEmailAndPassword(email, password)
                .addOnCompleteListener(new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        Log.d("MainActivity", "signIn:onComplete:" + task.isSuccessful());
                        hideProgressDialog();

                        if (task.isSuccessful()) {
                            Intent intent=new Intent(MainActivity.this,DashBoardActivity.class);
                            startActivity(intent);
                            finish();
                        } else {
                            Toast.makeText(MainActivity.this, "Sign In Failed",
                                    Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }

    private void signUp() {
        Log.d("MainActivity", "signUp");
        if (!validateForm()) {
            return;
        }

        showProgressDialog();
        String email = mEmailField.getText().toString();
        String password = mPasswordField.getText().toString();
    // to sign up the user at firebase
        mAuth.createUserWithEmailAndPassword(email, password)
                .addOnCompleteListener(new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        Log.d("MainActivity", "createUser:onComplete:" + task.isSuccessful());
                        hideProgressDialog();

                        if (task.isSuccessful()) {
                            Toast.makeText(MainActivity.this, "Successful! Please Sign In",
                                    Toast.LENGTH_SHORT).show();
                        } else {
                            Toast.makeText(MainActivity.this, "Sign Up Failed",
                                    Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }

    public void showProgressDialog() {
        if (mProgressDialog == null) {
            mProgressDialog = new ProgressDialog(this);
            mProgressDialog.setCancelable(false);
            mProgressDialog.setMessage("Loading...");
        }

        mProgressDialog.show();
    }

    public void hideProgressDialog() {
        if (mProgressDialog != null && mProgressDialog.isShowing()) {
            mProgressDialog.dismiss();
        }
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

layout for DashBoardActivity which will be shown to the user once a user is logged in.

activity_dashboard.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:id="@+id/savedetails"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:text="Save Details"/>

    <Button
        android:id="@+id/showusers"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:text="Show Users"/>

</LinearLayout>

DashBoardAcivity

package com.coderzpassion.firebasesample;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;

/**
 * Created by coderzpassion on 31/07/16.
 */
public class DashBoardActivity extends AppCompatActivity {

    Button savedetails,getusers;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dashboard);
        savedetails=(Button)findViewById(R.id.savedetails);
        getusers=(Button)findViewById(R.id.showusers);
        
        // to save user details call HomeActivity
        savedetails.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(DashBoardActivity.this,HomeActivity.class);
                startActivity(intent);
            }
        });
       // to get user details call ShowUsers Activity
        getusers.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(DashBoardActivity.this,ShowUsers.class);
                startActivity(intent);
            }
        });
    }
}

Create a Model Class as User.java to save user properties.

package com.coderzpassion.firebasesample.model;

/**
 * Created by coderzpassion on 31/07/16.
 */
public class User {
    private String firstname="";
    private String lastname="";
    private String age="";
    private String email="";

    public User()
    {

    }

    public String getFirstname() {
        return firstname;
    }

    public void setFirstname(String firstname) {
        this.firstname = firstname;
    }

    public String getLastname() {
        return lastname;
    }

    public void setLastname(String lastname) {
        this.lastname = lastname;
    }

    public String getAge() {
        return age;
    }

    public void setAge(String age) {
        this.age = age;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }
}

create a layout to allow the user to enter first-name, Lastname, age, email and then save at Firebase.

activity_home.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="First Name:"/>
        <EditText
            android:id="@+id/fname"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:hint="Enter your First name"/>

    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Last Name:"/>
        <EditText
            android:id="@+id/lname"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:hint="Enter your Last name"/>

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Age:"/>
        <EditText
            android:id="@+id/age"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:hint="Enter your age"/>

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Email:"/>
        <EditText
            android:id="@+id/email"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:hint="Enter your email"/>

    </LinearLayout>

    <Button
        android:id="@+id/save"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Save"/>


</LinearLayout>

HomeActivity.java

package com.coderzpassion.firebasesample;

import android.os.Bundle;
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.Toast;

import com.coderzpassion.firebasesample.model.User;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;

/**
 * Created by coderzpassion on 31/07/16.
 */
public class HomeActivity extends AppCompatActivity {

     EditText fname,lname,age,email;
     Button save;

    private DatabaseReference mDatabase;
    private FirebaseAuth mAuth;

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

        mDatabase = FirebaseDatabase.getInstance().getReference();
        mAuth = FirebaseAuth.getInstance();

        fname=(EditText)findViewById(R.id.fname);
        lname=(EditText)findViewById(R.id.lname);
        age=(EditText)findViewById(R.id.age);
        email=(EditText)findViewById(R.id.email);
        save=(Button)findViewById(R.id.save);
        save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if(validateForm())
                {
                    String frstname=fname.getText().toString().trim();
                    String lstname=lname.getText().toString().trim();
                    String ae=age.getText().toString().trim();
                    String ema=email.getText().toString().trim();
                    // create user object and set all the properties 
                    User user=new User();
                    user.setFirstname(frstname);
                    user.setLastname(lstname);
                    user.setAge(ae);
                    user.setEmail(ema);

                    if(mAuth.getCurrentUser()!=null)
                    {
                        // save the user at UserNode under user UID
                        mDatabase.child("UserNode").child(mAuth.getCurrentUser().getUid()).setValue(user, new DatabaseReference.CompletionListener() {
                            @Override
                            public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
                           if(databaseError==null)
                           {
                               Toast.makeText(HomeActivity.this, "Data is saved successfully",
                                       Toast.LENGTH_SHORT).show();
                               finish();
                           }
                            }
                        });
                    }

                }
            }
        });
    }

    // to check if user filled all the required fieds
    public boolean validateForm()
    {
        boolean alldone=true;
        String frstname=fname.getText().toString().trim();
        String lstname=lname.getText().toString().trim();
        String ae=age.getText().toString().trim();
        String ema=email.getText().toString().trim();

        if(TextUtils.isEmpty(frstname))
        {
            fname.setError("Enter your first name");

            return false;
        }else
        {
            alldone=true;
            fname.setError(null);
        }
        if(TextUtils.isEmpty(lstname))
        {
           lname.setError("Enter your last name");
            return false;
        }else
        {
            alldone=true;
            lname.setError(null);
        }
        if(TextUtils.isEmpty(ae))
        {
            age.setError("Enter your Age");
            return false;
        }else
        {
            alldone=true;
            age.setError(null);
        }
        if(TextUtils.isEmpty(ema))
        {
            email.setError("Enter your Email");
            return false;
        }else
        {
            alldone=true;
            email.setError(null);
        }
        return alldone;

    }
}

Now create an Adapter class to show Username and User email and then set it to Listview.

layout for adapter containing two text view one for username and other for user email.

adapter_listing.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="120dp">

   <TextView
       android:id="@+id/user_fullname"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:layout_alignParentLeft="true"
       android:textSize="12dp"/>

    <TextView
        android:id="@+id/user_email"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:textSize="12dp"/>


</RelativeLayout>

ListingAdapter.java

private class ListingAdapter extends BaseAdapter {

       Context context;
       LayoutInflater layoutInflater;
       ArrayList<User> users;

       public ListingAdapter(Context con,ArrayList<User> users)
       {
           context=con;
           layoutInflater = LayoutInflater.from(context);
           this.users=users;
       }

       @Override
       public int getCount() {
           return users.size();
       }

       @Override
       public View getView(int position, View convertView, ViewGroup parent) {
           ViewHolder holder;

           if (convertView == null) {
               convertView = layoutInflater.inflate(R.layout.adapter_listing, null, false);
               holder = new ViewHolder();

               holder.fullname = (TextView) convertView.findViewById(R.id.user_fullname);
               holder.email = (TextView) convertView.findViewById(R.id.user_email);
               convertView.setTag(holder);

           } else {
               holder = (ViewHolder) convertView.getTag();
           }

           User user=users.get(position);

           holder.fullname.setText(user.getFirstname()+user.getLastname());
           holder.email.setText(user.getEmail());

           return convertView;
       }

      public class ViewHolder {
           TextView fullname, email;

       }
       @Override
       public Object getItem(int position) {
           return users.get(position);
       }

       @Override
       public long getItemId(int position) {
           return position;
       }
   }

Create a layout for Activity to show users in Listview.

activity_showusers.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ListView
        android:id="@+id/allusers"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

    </ListView>

</LinearLayout>

ShowUsers.java

package com.coderzpassion.firebasesample;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.coderzpassion.firebasesample.model.User;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;

import java.util.ArrayList;

/**
 * Created by coderzpassion on 31/07/16.
 */
public class ShowUsers extends AppCompatActivity {

    ListView allusers;
    ProgressDialog mProgressDialog;
    DatabaseReference databaseReference= FirebaseDatabase.getInstance().getReference();
    ListingAdapter adapter;
    ArrayList<User> users=new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_showusers);
        allusers=(ListView)findViewById(R.id.allusers);
        adapter=new ListingAdapter(ShowUsers.this,users);
        allusers.setAdapter(adapter);
        getDataFromServer();
    }

    // getting the data from UserNode at Firebase and then adding the users in Arraylist and setting it to Listview
    public void getDataFromServer()
    {
        showProgressDialog();
        databaseReference.child("UserNode").addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                if(dataSnapshot.exists())
                {

                    for(DataSnapshot postSnapShot:dataSnapshot.getChildren())
                    {
                        User user=postSnapShot.getValue(User.class);
                        users.add(user);
                        adapter.notifyDataSetChanged();
                    }


                }
                hideProgressDialog();
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {
                hideProgressDialog();
            }
        });
    }
    private void showProgressDialog() {
        if (mProgressDialog == null) {
            mProgressDialog = new ProgressDialog(ShowUsers.this);
            mProgressDialog.setMessage("Loading...");
            mProgressDialog.setIndeterminate(true);
        }

        mProgressDialog.show();
    }

    private void hideProgressDialog() {
        if (mProgressDialog != null && mProgressDialog.isShowing()) {
            mProgressDialog.dismiss();
        }
    }


    private class ListingAdapter extends BaseAdapter {

        Context context;
        LayoutInflater layoutInflater;
        ArrayList<User> users;

        public ListingAdapter(Context con,ArrayList<User> users)
        {
            context=con;
            layoutInflater = LayoutInflater.from(context);
            this.users=users;
        }

        @Override
        public int getCount() {
            return users.size();
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder;

            if (convertView == null) {
                convertView = layoutInflater.inflate(R.layout.adapter_listing, null, false);
                holder = new ViewHolder();

                holder.fullname = (TextView) convertView.findViewById(R.id.user_fullname);
                holder.email = (TextView) convertView.findViewById(R.id.user_email);
                convertView.setTag(holder);

            } else {
                holder = (ViewHolder) convertView.getTag();
            }

            User user=users.get(position);

            holder.fullname.setText(user.getFirstname()+user.getLastname());
            holder.email.setText(user.getEmail());

            return convertView;
        }

       public class ViewHolder {
            TextView fullname, email;

        }
        @Override
        public Object getItem(int position) {
            return users.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }
    }
}

For official documentation Refer at Following link:-

saving data at firebase

Output

workingwithfirebase successfulsignin usersavedsuccessfullyatfirebase savinguseratfirebaseandroid  showusersfromfirebaseandroid

Database at Firebase

databaseatfirebase

Android Starting with Firebase

As most of you are knowing Firebase is on boom these days. Firebase is a platform for the web,mobile applications which provide real-time database,storage,authentication, Fcm, push notifications easily and is fast and reliable. Firebase is considered as the alternative of Parse.com

So,let’s start using Firebase for android.

1. First of all, create Firebase account using Gmail id ( Firebase Console ).

firebaseandroid

2. Create a project in Firebase by clicking on create project button, then enter the project name and select a country and then click on next.

Androidworkingwithfirebase

3. Then enter package name of the project and click next, it will download JSON file which will be used in the android studio to integrate your project with Firebase.

creatingandroidproject

createproject

Now, Create a project in Android studio using same package name which you used while creating the project in Firebase.

After creating a project in Android Studio add a dependency in module build.Gradle file

compile 'com.google.firebase:firebase-auth:9.0.0'   //for autheticating the user

then add the JSON file under module app root directly and then add the classpath in project build.Gradle file

classpath 'com.google.gms:google-services:3.0.0'

Then add the plugin in Module’s build.gradle file.

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

Let’s Enable Sign-in-method at Firebase. Click on Auth present at the left side and then click on Sign-in-method and enable the First option under Providers i.e Email/Password.

Screen Shot 2016-07-30 at 3.26.51 PM

Now, let’s create a layout for Activity containing Two Editext for email and password and two buttons for signup and sign in.

activity_signin.xml 

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.database.sample.jagjit.singh.SignInActivity">

    <LinearLayout
        android:id="@+id/layout_email_password"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/icon"
        android:layout_centerHorizontal="true"
        android:orientation="horizontal">

        <EditText
            android:id="@+id/field_email"
            android:layout_width="150dp"
            android:layout_height="wrap_content"
            android:ellipsize="end"
            android:gravity="center_horizontal"
            android:hint="@string/hint_email"
            android:inputType="textEmailAddress"
            android:maxLines="1" />

        <EditText
            android:id="@+id/field_password"
            android:layout_width="150dp"
            android:layout_height="wrap_content"
            android:ellipsize="end"
            android:gravity="center_horizontal"
            android:hint="@string/hint_password"
            android:inputType="textPassword"
            android:maxLines="1" />

    </LinearLayout>

    <LinearLayout
        android:id="@+id/layout_buttons"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/layout_email_password"
        android:layout_centerHorizontal="true"
        android:orientation="horizontal">

        <Button
            android:id="@+id/button_sign_in"
            android:layout_width="150dp"
            android:layout_height="wrap_content"
            android:text="@string/sign_in" />


        <Button
            android:id="@+id/button_sign_up"
            android:layout_width="150dp"
            android:layout_height="wrap_content"
            android:text="@string/sign_up" />

    </LinearLayout>


</RelativeLayout>

Create an Activity to Sign in and Sign up the user with required credentials.

Code to Validate whether the user entered both Email and Password ,returns true if both fields are entered.

private boolean validateForm() {
       boolean result = true;
       if (TextUtils.isEmpty(mEmailField.getText().toString())) {
           mEmailField.setError("Required");
           result = false;
       } else {
           mEmailField.setError(null);
       }

       if (TextUtils.isEmpty(mPasswordField.getText().toString())) {
           mPasswordField.setError("Required");
           result = false;
       } else {
           mPasswordField.setError(null);
       }

       return result;
   }

Code to Signup the user.

private void signUp() {
        Log.d("MainActivity", "signUp");
        if (!validateForm()) {
            return;
        }

        showProgressDialog();
        String email = mEmailField.getText().toString();
        String password = mPasswordField.getText().toString();

        mAuth.createUserWithEmailAndPassword(email, password)
                .addOnCompleteListener(new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        Log.d("MainActivity", "createUser:onComplete:" + task.isSuccessful());
                        hideProgressDialog();

                        if (task.isSuccessful()) {
                            Toast.makeText(MainActivity.this, "Successful! Please Sign In",
                                    Toast.LENGTH_SHORT).show();
                        } else {
                            Toast.makeText(MainActivity.this, "Sign Up Failed",
                                    Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }

Code to Sign In the user.

private void signIn() {
       Log.d("MainActivity", "signIn");
       if (!validateForm()) {
           return;
       }

       showProgressDialog();
       String email = mEmailField.getText().toString();
       String password = mPasswordField.getText().toString();

       mAuth.signInWithEmailAndPassword(email, password)
               .addOnCompleteListener(new OnCompleteListener<AuthResult>() {
                   @Override
                   public void onComplete(@NonNull Task<AuthResult> task) {
                       Log.d("MainActivity", "signIn:onComplete:" + task.isSuccessful());
                       hideProgressDialog();

                       if (task.isSuccessful()) {
                           Toast.makeText(MainActivity.this, "Sign In Successful",
                                   Toast.LENGTH_SHORT).show();
                       } else {
                           Toast.makeText(MainActivity.this, "Sign In Failed",
                                   Toast.LENGTH_SHORT).show();
                       }
                   }
               });
   }

Full code MainActivity.java

package com.coderzpassion.firebasesample;

import android.app.ProgressDialog;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
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;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{

    private FirebaseAuth mAuth;

    private EditText mEmailField;
    private EditText mPasswordField;
    private Button mSignInButton;
    private Button mSignUpButton;

    private ProgressDialog mProgressDialog;

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

        // Views
        mEmailField = (EditText) findViewById(R.id.field_email);
        mPasswordField = (EditText) findViewById(R.id.field_password);
        mSignInButton = (Button) findViewById(R.id.button_sign_in);
        mSignUpButton = (Button) findViewById(R.id.button_sign_up);

        // Click listeners
        mSignInButton.setOnClickListener(this);
        mSignUpButton.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.button_sign_in:
                signIn();
                break;
            case R.id.button_sign_up:
                signUp();
                break;
        }

    }

    private boolean validateForm() {
        boolean result = true;
        if (TextUtils.isEmpty(mEmailField.getText().toString())) {
            mEmailField.setError("Required");
            result = false;
        } else {
            mEmailField.setError(null);
        }

        if (TextUtils.isEmpty(mPasswordField.getText().toString())) {
            mPasswordField.setError("Required");
            result = false;
        } else {
            mPasswordField.setError(null);
        }

        return result;
    }

    private void signIn() {
        Log.d("MainActivity", "signIn");
        if (!validateForm()) {
            return;
        }

        showProgressDialog();
        String email = mEmailField.getText().toString();
        String password = mPasswordField.getText().toString();

        mAuth.signInWithEmailAndPassword(email, password)
                .addOnCompleteListener(new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        Log.d("MainActivity", "signIn:onComplete:" + task.isSuccessful());
                        hideProgressDialog();

                        if (task.isSuccessful()) {
                            Toast.makeText(MainActivity.this, "Sign In Successful",
                                    Toast.LENGTH_SHORT).show();
                        } else {
                            Toast.makeText(MainActivity.this, "Sign In Failed",
                                    Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }

    private void signUp() {
        Log.d("MainActivity", "signUp");
        if (!validateForm()) {
            return;
        }

        showProgressDialog();
        String email = mEmailField.getText().toString();
        String password = mPasswordField.getText().toString();

        mAuth.createUserWithEmailAndPassword(email, password)
                .addOnCompleteListener(new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        Log.d("MainActivity", "createUser:onComplete:" + task.isSuccessful());
                        hideProgressDialog();

                        if (task.isSuccessful()) {
                            Toast.makeText(MainActivity.this, "Successful! Please Sign In",
                                    Toast.LENGTH_SHORT).show();
                        } else {
                            Toast.makeText(MainActivity.this, "Sign Up Failed",
                                    Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }

    public void showProgressDialog() {
        if (mProgressDialog == null) {
            mProgressDialog = new ProgressDialog(this);
            mProgressDialog.setCancelable(false);
            mProgressDialog.setMessage("Loading...");
        }

        mProgressDialog.show();
    }

    public void hideProgressDialog() {
        if (mProgressDialog != null && mProgressDialog.isShowing()) {
            mProgressDialog.dismiss();
        }
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

Output

workingwithfirebase   successfullysignedup   successfulsignin

For official documentation:- Refer here

Next Step, Once User is log in, next time we can directly show the user any Activity as per Requirement.

To check if user is already logged In

 if (mAuth.getCurrentUser() != null) {
            // user is already log in
        // show Home Activity
        }
else
{
//ask the user to sign in
signIn();
}