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();
}