Getting started with Firebase

FIREBASE ANDROID DATABASE

Firebase is a Backend-as-a-Service platform developed by Firebase Inc. then acquired by Google. Firebase provides you full access of tools which helps you to focus on user experience. So you don't need to manage servers and don't need to write APIs. In this tutorial, we will learn how to integrate Firebase in your project and make simple login amd registration functionality.

Generic placeholder image

Getting Started

First, you will need a account to use Firebase. You can create free account at https://firebase.google.com/

Configure Firebase

For login, go the top-right corner and press GO TO CONSOLE and put login details. After login, you will see Firebase dashboard.
Generic placeholder image

  1. To create your first project click the + Add project.

  2. Now, you will see Add a project window, fill Project Name and select your Country/region and click Create Project.


  3. Generic placeholder image

  4. You will see project dashboard, go to Add Firebase to your Android App circle.

  5. In next window enter your Android package name and hit Register App button.

    Generic placeholder image

  6. In next step download google-services.json file.We will use this file later and just press Next.

    Generic placeholder image

  7. Next step is for adding dependencies so just skip it because we will add dependencies later in this tutorial.

  8. Now you will see project's dashboard.Go to Develop > Authentication > Sign-in Method and press Email/Password option.

  9. In next window Enable Email/Password and click Save

    Generic placeholder image

Now, we can use Firebase in Android Studio project.


Creating Android Project

  1. Create a new project in Android Studio.Go to File > New > New Project.
  2. In next window enter Application Name, Company domain, and Package name same package name as Firebase console and press Next.
  3. Now select target Android devices and press Next.
  4. Choose Empty Activity in next window.
  5. Now, enter activity name and layout name and press Finish.

Integrating into project

  1. Switch your project view to Project and paste downloaded google-services.json file to app directory.
  2. Open build.gradle file in Project-level home directory and add following line.
    	 
    dependencies {
    classpath 'com.android.tools.build:gradle:3.1.2'
    //Add this line
    classpath 'com.google.gms:google-services:3.3.1'
    }
    	 
    	 


    Now, open App-level app/build.gradle file and add following three lines.
    	 
    dependencies {
        implementation fileTree(dir: 'libs', include: ['*.jar'])
        implementation 'com.android.support:appcompat-v7:27.1.1'
        implementation 'com.android.support.constraint:constraint-layout:1.1.0'
        testImplementation 'junit:junit:4.12'
        androidTestImplementation 'com.android.support.test:runner:1.0.2'
        androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
    	//Add this line
        implementation 'com.google.firebase:firebase-core:15.0.2'
    	implementation 'com.google.firebase:firebase-auth:15.1.0'
    }
    //Add this line to bottom of file
    apply plugin: 'com.google.gms.google-services'
    	 
    	 

    Finally, press Sync Now in the bar and you are ready to use Firebase in your Android project.

  3. Open AndroidManifest.xml file and add INTERNET permission.
    <uses-permission android:name="android.permission.INTERNET" />
  4. Create Login and Signin activity

  5. Create new activity named LoginSignupActivty.java and add following code
    		
    package firebase.gurjits.com.firebasedemo;
    
    import android.support.annotation.NonNull;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    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.auth.FirebaseUser;
    
    public class LoginSignupActivity extends AppCompatActivity {
    
        private EditText editTextEmail, editTextPassword;
        private Button buttonSignIn, buttonSignUp;
        private FirebaseAuth mAuth;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.login_signup_activity);
    
            mAuth = FirebaseAuth.getInstance();
    
            editTextEmail = (EditText) findViewById(R.id.signup_email);
            editTextPassword = (EditText) findViewById(R.id.signup_password);
            buttonSignUp = (Button) findViewById(R.id.signup_btn);
            buttonSignIn = (Button) findViewById(R.id.login_btn);
            buttonSignIn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    String signinEmail = editTextEmail.getText().toString().trim();
                    String signinPassword = editTextPassword.getText().toString().trim();
    
                    //checking if any field is empty
                    if (signinEmail.isEmpty()) {
                        Toast.makeText(LoginSignupActivity.this, "Please enter your email", Toast.LENGTH_LONG).show();
                    } else if (signinPassword.isEmpty()) {
                        Toast.makeText(LoginSignupActivity.this, "Please enter your password", Toast.LENGTH_LONG).show();
                    } else {
                        mAuth.signInWithEmailAndPassword(signinEmail, signinPassword)
                                .addOnCompleteListener(LoginSignupActivity.this, new OnCompleteListener() {
                                    @Override
                                    public void onComplete(@NonNull Task task) {
                                        if (task.isSuccessful()) {
                                            // Sign in success
                                            FirebaseUser user = mAuth.getCurrentUser();
                                            Toast.makeText(LoginSignupActivity.this, "Authentication successful. " + user,
                                                    Toast.LENGTH_SHORT).show();
                                        } else {
                                            // If sign in fails
                                            Toast.makeText(LoginSignupActivity.this, "Authentication failed.",
                                                    Toast.LENGTH_SHORT).show();
                                        }
    
                                        // ...
                                    }
                                });
    
                    }
                }
            });
    
            buttonSignUp.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    String getEmail = editTextEmail.getText().toString().trim();
                    String getPassword = editTextPassword.getText().toString().trim();
    
                    //checking if any field is empty
                    if (getEmail.isEmpty()) {
                        Toast.makeText(LoginSignupActivity.this, "Please enter your email", Toast.LENGTH_LONG).show();
                    } else if (getPassword.isEmpty()) {
                        Toast.makeText(LoginSignupActivity.this, "Please enter your password", Toast.LENGTH_LONG).show();
                    } else {
                        mAuth.createUserWithEmailAndPassword(getEmail, getPassword)
                                .addOnCompleteListener(LoginSignupActivity.this, new OnCompleteListener() {
                                    @Override
                                    public void onComplete(@NonNull Task task) {
                                        if (task.isSuccessful()) {
                                            // Successfully Sign in
                                            FirebaseUser user = mAuth.getCurrentUser();
                                            Toast.makeText(LoginSignupActivity.this, "Authentication successful.",
                                                    Toast.LENGTH_SHORT).show();
                                        } else {
                                            // If sign in fails
                                            Toast.makeText(LoginSignupActivity.this, "Authentication failed.",
                                                    Toast.LENGTH_SHORT).show();
                                        }
    
                                        // ...
                                    }
                                });
    
                    }
    
                }
            });
        }
    
        @Override
        protected void onStart() {
            super.onStart();
            FirebaseUser currentUser = mAuth.getCurrentUser();
            if (currentUser != null) {
                Toast.makeText(LoginSignupActivity.this, "Already Login", Toast.LENGTH_LONG).show();
            }
        }
    }
    
    		
    		

  6. Open login_signup_activity.xml file and add following lines
    		
    <?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"
        android:padding="10dp"
        tools:context=".LoginSignupActivity">
    
        <ImageView
            android:id="@+id/imageview_logo"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:paddingBottom="10dp"
            android:src="@drawable/firebase_logo" />
    
        <TextView
            android:id="@+id/text_signin"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:paddingBottom="20dp"
            android:text="@string/signin_text"
            android:textSize="24dp" />
    
        <EditText
            android:id="@+id/signup_email"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="@string/email_hint"
            android:inputType="textEmailAddress" />
    
        <EditText
            android:id="@+id/signup_password"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="@string/password_hint"
            android:inputType="textPassword" />
    
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">
    
            <Button
                android:id="@+id/login_btn"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginRight="5dp"
                android:layout_weight="1"
                android:background="@color/colorAccent"
                android:text="@string/signin"
                android:textColor="@android:color/white" />
    
            <Button
                android:id="@+id/signup_btn"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:background="@color/colorPrimary"
                android:text="@string/signup"
                android:textColor="@android:color/white" />
    
        </LinearLayout>
    
    </LinearLayout>
    
    		
    		

  7. Now Run the application and you will see the following result. Generic placeholder image

Gurjit Singh

Hey there! I'm an experienced Android developer and a geek interested in the newest technologies and trends.