Android – Getting Started with Firebase – 1

In this tutorial we will learn about Firebase from Google I/O. To learn about Firebase, here we will create a login and registration page using Firebase Email & Password Authentication. Firebase is introduced with bunch of features for our android app starting from authentication to hosting our app.

1. Enabling Firebase Auth

  • First of all we will go to https://firebase.google.com/ and make an Firebase account to gain access to their console.
  • Click on “GET STARTED FOR FREE” on that page to create account.
  • Login through your Gmail Account. After login you will be redirected to the Firebase Console.
  • Now on the console page click on “CREATE NEW PROJECT“.
  • Fill the Project name and select the Country and click on CREATE PROJECT. Here I am taking Project name as “Authentication” and Country as “India“.
  • Now click on “Add Firebase to your Android App” on your console screen.
  • Fill the “Package Name” and leave “Debug signing certificate SHA-1” as blank and click on “ADD APP“. Here I am taking package name as “net.apptronix.www.firebase_authentication“. Here the google-services.json file will be downloaded when you press Add App button.
  • After this click on “Continue” and “Finish“.
  • Now on the project dashboard click on the “Auth” on left hand side and click “Set Up Sign-In Method” and choose Email & Password and enable it and then click on Save.
  • Now we are all set to create our Android Project. In this app we will use Firebase Authentication in which we will learn to  to add Login, Registration, Forgot Password, Change Email, Change Password & Sign Out option.

2. Creating Android Project

  • Create a new project in Android Studio from File ⇒ New ⇒ New Project. Give the Application Name and Package Name. While giving Package name, give the same package name that we have given during the Firebase Console. For me its net.apptronix.www.firebase_authentication
  • Select Blank Activity when it asks you to set default activity and proceed and lastly click on Finish.
  • Now open AndroidManifest.xml that is inside manifest folder on the left and add the INTERNET permission as we have to use internet in our app.
<uses-permission android:name="android.permission.INTERNET"/>
  • Paste the google-services.json file that we have downloaded previously to our project’s app folder. This step is very important as your project won’t build without this file.
  • Now open the build.gradle located in project’s home directory and add firebase dependency. We have to build.gradle file, one is in the project’s home directory and other is in the app folder. So we have to add dependencies on the file in the home directory.
dependencies {
    classpath 'com.android.tools.build:gradle:2.2.1'
    classpath 'com.google.gms:google-services:3.0.0'
    // NOTE: Do not place your application dependencies here; they belong
    // in the individual module build.gradle files
}
  • Open app/build.gradle and add firebase auth dependency and at the very bottom of the file, add apply plugin: ‘com.google.gms.google-services’. We have to open build.gradle file which is inside the app folder.
dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:23.4.0'
    compile "com.google.firebase:firebase-auth:9.0.2"
    testCompile 'junit:junit:4.12'
}
apply plugin: 'com.google.gms.google-services'
  • Click on Sync Now that must be coming on top right corner.
  • Now we will make some activities :
    • SignUpActivity
    • LoginActivity
    • ResetPasswordActivity
    • & MainActivity will be our Profile Activity that we will get after logging in.
  • Right click on app folder go to New ⇒ Activity ⇒ Empty Activity
  • Give the Activity Name as “SignUpActivity” and leave all thing as default and click on Finish.
  • Similarly make two more activities named LoginActivity & ResetPasswordActivity.

2.1 Sign Up with Email & Password

  • In this activity we will take two EditText fields for Email & Password, & three buttons for Register and navigating to Login & Forgot Password activity.
  • Go to res ⇒ layout ⇒ activity_sign_up.xml and paste the following code there.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:tools="http://schemas.android.com/tools"
            android:id="@+id/activity_sign_up"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical"
            tools:context="net.apptronix.www.firebase_authentication.SignUpActivity">
        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:gravity="center"
            android:orientation="vertical"
            android:padding="@dimen/activity_horizontal_margin">
        <TextView
            android:text="Sign Up Here"
            android:gravity="center"
            android:textSize="30dp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/textView"
            android:textColor="#123"
            android:layout_marginBottom="30dp"/>
        <EditText
            android:id="@+id/emailid"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Enter Email Id"
            android:inputType="textEmailAddress"
            android:maxLines="1"
            android:singleLine="true"
            android:textColor="#123" />
        <EditText
            android:id="@+id/pass"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:focusableInTouchMode="true"
            android:hint="Enter Password"
            android:inputType="textPassword"
            android:maxLines="1"
            android:singleLine="true"
            android:textColor="#123" />
        <Button
            android:id="@+id/register_button"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="16dp"
            android:background="@color/colorAccent"
            android:onClick="register"
            android:text="Register"
            android:textSize="20dp"
            android:textColor="@android:color/black"
            android:textStyle="bold" />
        <Button
            android:id="@+id/reset_pass_btn"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="20dip"
            android:background="@null"
            android:onClick="reset"
            android:text="Forgot Password"
            android:textAllCaps="false"
            android:textSize="20dp"
            android:textColor="@color/colorAccent" />
        <Button
            android:id="@+id/login_btn"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="20dip"
            android:background="@null"
            android:textColor="#123"
            android:onClick="login"
            android:text="Already Registered? Login"
            android:textAllCaps="false"
            android:textSize="20dp" />

        </LinearLayout>

</LinearLayout>
  • Now Go to SignUpActivity.java file and paste the following code just below the package line. Here we will use createUserWithEmailAndPassword() provided by Firebase, a method to create a new user with email and password.
import android.app.ProgressDialog;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
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;
public class SignUpActivity extends AppCompatActivity {
    EditText email,password;
    FirebaseAuth auth;
    ProgressDialog pd;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sign_up);
        email=(EditText)findViewById(R.id.emailid);
        password=(EditText)findViewById(R.id.pass);
        auth = FirebaseAuth.getInstance();
        pd=new ProgressDialog(SignUpActivity.this);
    }
    public void register(View v)
    {
        String email_txt = email.getText().toString();
        String password_txt = password.getText().toString();
        if (TextUtils.isEmpty(email_txt)) {
            Toast.makeText(getApplicationContext(), "Enter email address!", Toast.LENGTH_SHORT).show();
            return;
        }
        if (TextUtils.isEmpty(password_txt)) {
            Toast.makeText(getApplicationContext(), "Enter password!", Toast.LENGTH_SHORT).show();
            return;
        }
        if (password.length() < 6) {
            Toast.makeText(getApplicationContext(), "Password too short, enter minimum 6 characters!", Toast.LENGTH_SHORT).show();
            return;
        }
        pd.setMessage("Please Wait");
        pd.setCancelable(true);
        pd.show();
        auth.createUserWithEmailAndPassword(email_txt, password_txt)
                .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(Task<AuthResult> task) {
                        pd.dismiss();
                        // If registration fails, display a message to the user.
                        // If registration succeed it will take us to the Login Activity
                        if (!task.isSuccessful()) {
                            Toast.makeText(SignUpActivity.this, "Authentication failed." + task.getException(),
                                    Toast.LENGTH_LONG).show();
                        } else {
                            startActivity(new Intent(SignUpActivity.this, LoginActivity.class));
                            Toast.makeText(SignUpActivity.this, "Registration Successful",
                                    Toast.LENGTH_LONG).show();
                            finish();
                        }
                    }
                });
    }
    public void reset(View v)
    {
        startActivity(new Intent(this, ResetPasswordActivity.class));
    }
    public void login(View v)
    {
        startActivity(new Intent(this, LoginActivity.class));
    }
}
  • Lastly open AndroidManifest.xml file and make SignUpActivity as launcher activity (for now) and test the sign up process.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="net.apptronix.www.firebase_authentication">
    <uses-permission android:name="android.permission.INTERNET" />
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="Firebase"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
        </activity>
        <activity android:name=".LoginActivity" />
        <activity android:name=".SignUpActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
            </activity>
        <activity android:name=".ResetPasswordActivity"></activity>
    </application>
</manifest>
  • Ok now run the app and check either your SignUpActivity is working or not. You will get the following output.
  • After SignUp, login to your Firebase account again and go to the Firebase Console and click on Auth. Here you will see that user is successfully registered with desired email and password that you have provided in the app.
  • Congrats !! Now we can create user with email and password in Firebase.
  • Now we will learn about LoginActivity, ResetPasswordActivity and MainActivity in our next tutorial. Thank you for visiting this tutorial. If you have any doubts or queries regarding this, you can comment below in our comment section. Please check our next part for remaining part of this tutorial.

Next Part : Android – Getting Started with Firebase – 2

© Copyright 2016 – Apptronix Technologies. All Rights Reserved. ISO 9001:2015 Certified