Firebase using Android Studio : Part 2 : SignIn form using Firebase

SignIn/SignUp/SignOut using Google Firebase on Android Studio :

In our last tutorial, we learned how to create a Firebase Project and how to make ready Android Studio for Firebase . In this tutorial , we will check how to create a new user account using email/password and login/logout to the account.
      1. Create a new Project in Android Studio  File -> New -> New Project. Remember to use same package name for this project as we have defined in our last tutorial. For me it was “com.codevscolor.firebasedemo”. Create this project with a Simple activity MainActivity.

      2. Paste the google-services.json file you have downloaded previously to the “app/” folder.

      3. We will need internet connection for our project to connect to google Firebase . Add internet permission inside your “AndroidManifest.xml” file

<uses-permission android:name="android.permission.INTERNET" />

      4. Add the following dependencies inside your build.gradle file located in your home directory.

classpath 'com.android.tools.build:gradle:2.2.2'
classpath 'com.google.gms:google-services:3.0.0'


Google Firebase using android studio

 

 

 

 

 

 

 

 

5. Now add firebase auth dependency on your app/build.gradle file. You can always find out latest dependencies for firebase here 

For my project , final build.gradle file looks like :

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

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.1"
    defaultConfig {
        applicationId "com.codevscolor.firebasedemo"
        minSdkVersion 9
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:25.0.1'
    compile "com.google.firebase:firebase-auth:10.0.1"
}


Note : If your gradle sync is failing , click on Tools -> Android -> SDK Manager , 
Click on SDK Tools tab and install “Google Play Services” and “Google Repository” both.

SignUp to Google Firebase using email and password :

1. Firebase provides a method createUserWithEmail to create a new user with email and password.

  1. Create one FirebaseAuth variable
    private FirebaseAuth auth;
  2.  Get the instance of the variable
    auth = FirebaseAuth.getInstance();
  3. Collect email and password and create one user :
    auth.createUserWithEmailAndPassword(emailText, pwdText).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
        @Override
        public void onComplete(@NonNull Task<AuthResult> task) {
            if (!task.isSuccessful()) {
             //failed
            } else {
              //success
                });
         
            }
        }
  4.  Create one new Activity SignupActivity with layout file as activity_signup.xml :

    Before signup, We will first check if any of the field is empty, is the email valid and password is more than 6 characters or not.If these checks are true, we will try to create one user on firebase database.

    SignupActivity.java 

    public class SignupActivity extends AppCompatActivity {
        private EditText etEmail;
        private EditText etPassword;
        private Button signUpButton;
    
        private String emailText;
        private String pwdText;
    
        private TextInputLayout emailLayout;
        private TextInputLayout pwdLayout;
        private FirebaseAuth auth;
        private Context context;
        private ProgressDialog progressDialog;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_signup);
    
            context = this;
    
            etEmail = (EditText) findViewById(R.id.signup_editTextEmail);
            etPassword = (EditText) findViewById(R.id.signup_editTextPassword);
            signUpButton = (Button) findViewById(R.id.signup_button);
    
            emailLayout = (TextInputLayout) findViewById(R.id.signup_layout_email);
            pwdLayout = (TextInputLayout) findViewById(R.id.signup_layout_password);
    
            progressDialog = new ProgressDialog(this);
            progressDialog.setMessage("Loading...");
            progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
    
            getSupportActionBar().setTitle("Sign Up");
    
            auth = FirebaseAuth.getInstance();
    
            signUpButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    hideSoftKeyboard();
                    progressDialog.show();
                    signUp();
                }
            });
    
        }
    
        private void hideSoftKeyboard(){
            InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), 0);
        }
    
    
        private void signUp() {
            emailText = etEmail.getText().toString().trim();
            pwdText = etPassword.getText().toString().trim();
    
            if (emailText.isEmpty()) {
                emailLayout.setError(getString(R.string.hint_empty));
            } else if (!android.util.Patterns.EMAIL_ADDRESS.matcher(emailText).matches()) {
                emailLayout.setError(getString(R.string.error_email));
            } else {
                emailLayout.setErrorEnabled(false);
            }
            if (pwdText.isEmpty()) {
                pwdLayout.setError(getString(R.string.hint_empty));
            } else if (pwdText.length() < 6) {
                pwdLayout.setError(getString(R.string.hint_pwd_min));
            } else {
                pwdLayout.setErrorEnabled(false);
            }
    
            if (!emailLayout.isErrorEnabled() && !pwdLayout.isErrorEnabled()) {
                auth.createUserWithEmailAndPassword(emailText, pwdText).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        if (!task.isSuccessful()) {
                            progressDialog.dismiss();
                            AlertDialog.Builder builder = new AlertDialog.Builder(context, R.style.DialogStyle);
                            builder.setMessage("Oops..please try again !!");
                            builder.setPositiveButton("OK", null);
                            builder.show();
                        } else {
                            progressDialog.dismiss();
                            AlertDialog.Builder builder = new AlertDialog.Builder(context, R.style.DialogStyle);
                            builder.setMessage("Yeah..one new user is created !!");
                            builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialogInterface, int i) {
                                    finish();
                                }
                            });
                            builder.show();
                        }
                    }
    
                });
    
    
            }else {
                progressDialog.dismiss();
            }
    
        }
    }

    activity_signup.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:background="@color/colorBack"
        android:focusable="true"
        android:focusableInTouchMode="true"
        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.codevscolor.firebasedemo.activity.MainActivity">
    
        <android.support.design.widget.TextInputLayout
            android:id="@+id/signup_layout_email"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textColorHint="@color/colorHint">
    
            <EditText
                android:id="@+id/signup_editTextEmail"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="@string/hint_email"
                android:inputType="textEmailAddress"
                android:textColor="@color/textColor" />
        </android.support.design.widget.TextInputLayout>
    
        <android.support.design.widget.TextInputLayout
            android:id="@+id/signup_layout_password"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@id/signup_layout_email"
            android:textColorHint="@color/colorHint">
    
            <EditText
                android:id="@+id/signup_editTextPassword"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="45dp"
                android:hint="@string/hint_password"
                android:inputType="textPassword"
                android:textColor="@color/textColor" />
        </android.support.design.widget.TextInputLayout>
    
        <Button
            android:id="@+id/signup_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentEnd="true"
            android:layout_alignParentLeft="true"
            android:layout_alignParentRight="true"
            android:layout_alignParentStart="true"
            android:layout_below="@+id/signup_layout_email"
            android:layout_marginTop="104dp"
            android:background="@color/buttoncolor"
            android:text="SignUp"
            android:textColor="@color/textColor" />
    
    </RelativeLayout>

    Run this application, signup one new user and check on Firebase Account :

    Google Firebase using android studio : signup

     

     

     

     

    Sign in :

    Sign in is similar to Sign Up. Following method is used for Sign in to Google firebase :
    1. Suppose the user logged in to the application, closed it and start it again. In this scenario, we need to check if the user is already logged in, and if true, show a different activity .

    In our example,

    MainActivity will work as SignIn Activity.We will add a login screen to our MainActivity.
    Update your MainActivity file as below :

    public class MainActivity extends AppCompatActivity {
        private EditText etEmail;
        private EditText etPassword;
        private Button loginButton;
    
        private String emailText;
        private String pwdText;
        private FirebaseAuth auth;
        private TextInputLayout emailLayout;
        private TextInputLayout pwdLayout;
        private TextView signUp;
        private ProgressDialog progressDialog;
    
        private TextView realTimeDataText;
        private TextView storageDatabase;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            etEmail = (EditText) findViewById(R.id.editTextEmail);
            etPassword = (EditText) findViewById(R.id.editTextPassword);
            loginButton = (Button) findViewById(R.id.button);
    
            progressDialog = new ProgressDialog(this);
            progressDialog.setMessage("Loading...");
            progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
    
    
            emailLayout = (TextInputLayout) findViewById(R.id.layout_email);
            pwdLayout = (TextInputLayout) findViewById(R.id.layout_password);
    
            signUp = (TextView) findViewById(R.id.signUp);
            realTimeDataText = (TextView)findViewById(R.id.realTimeDatabase);
    
            realTimeDataText.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent i = new Intent(MainActivity.this, RealTimeActivity.class);
                    startActivity(i);
                }
            });
    
            storageDatabase = (TextView)findViewById(R.id.storageDatabase);
            storageDatabase.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent i = new Intent(MainActivity.this, StorageActivity.class);
                    startActivity(i);
                }
            });
    
            auth = FirebaseAuth.getInstance();
    
    
            loginButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    hideSoftKeyboard();
                    progressDialog.show();
                    login();
                }
            });
    
            signUp.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent i = new Intent(MainActivity.this, SignupActivity.class);
                    startActivity(i);
                }
            });
    
            if(auth.getCurrentUser() != null){
                //user is logged in
                Intent i = new Intent(this,LogoutActivity.class);
                startActivity(i);
            }
    
    
        }
    
    
    
        private void hideSoftKeyboard(){
            InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), 0);
        }
    
        private void login() {
            emailText = etEmail.getText().toString().trim();
            pwdText = etPassword.getText().toString().trim();
    
            if (emailText.isEmpty()) {
                emailLayout.setError(getString(R.string.hint_empty));
            } else if (!android.util.Patterns.EMAIL_ADDRESS.matcher(emailText).matches()) {
                emailLayout.setError(getString(R.string.error_email));
            } else {
                emailLayout.setErrorEnabled(false);
            }
            if (pwdText.isEmpty()) {
                pwdLayout.setError(getString(R.string.hint_empty));
            } else if (pwdText.length() < 6) {
                pwdLayout.setError(getString(R.string.hint_pwd_min));
            } else {
                pwdLayout.setErrorEnabled(false);
            }
    
            if (!emailLayout.isErrorEnabled() && !pwdLayout.isErrorEnabled()) {
                auth.signInWithEmailAndPassword(emailText, pwdText).addOnCompleteListener(MainActivity.this, new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        if (!task.isSuccessful()) {
                            progressDialog.dismiss();
                            AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this, R.style.DialogStyle);
                            builder.setMessage("Login Failed !!");
                            builder.setPositiveButton("OK", null);
                            builder.show();
                        } else {
                            progressDialog.dismiss();
                            AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this, R.style.DialogStyle);
                            builder.setMessage("Login Successfull !!");
                            builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialogInterface, int i) {
                                    Intent intent = new Intent(MainActivity.this, LogoutActivity.class);
                                    startActivity(intent);
                                }
                            });
                            builder.show();
                        }
                    }
                });
    
    
            }else {
                progressDialog.dismiss();
            }
    
        }
    }

    and layout_activitymain as below :

    <?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:background="@color/colorBack"
        android:focusable="true"
        android:focusableInTouchMode="true"
        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.codevscolor.firebasedemo.activity.MainActivity">
    
        <android.support.design.widget.TextInputLayout
            android:id="@+id/layout_email"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textColorHint="@color/colorHint">
    
            <EditText
                android:id="@+id/editTextEmail"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="@string/hint_email"
                android:inputType="textEmailAddress"
                android:textColor="@color/textColor" />
        </android.support.design.widget.TextInputLayout>
    
        <android.support.design.widget.TextInputLayout
            android:id="@+id/layout_password"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@id/layout_email"
            android:textColorHint="@color/colorHint">
    
            <EditText
                android:id="@+id/editTextPassword"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="45dp"
                android:hint="@string/hint_password"
                android:inputType="textPassword"
                android:textColor="@color/textColor" />
        </android.support.design.widget.TextInputLayout>
    
        <Button
            android:id="@+id/button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentEnd="true"
            android:layout_alignParentLeft="true"
            android:layout_alignParentRight="true"
            android:layout_alignParentStart="true"
            android:layout_below="@+id/layout_email"
            android:layout_marginTop="104dp"
            android:background="@color/buttoncolor"
            android:text="Login"
            android:textColor="@color/textColor" />
    
        <TextView
            android:text="Sign Up"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/button"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="35dp"
            android:id="@+id/signUp" />
    
        <TextView
            android:text="Test RealTime Database"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/signUp"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="35dp"
            android:id="@+id/realTimeDatabase" />
    
        <TextView
            android:text="Test Storage"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/realTimeDatabase"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="35dp"
            android:id="@+id/storageDatabase" />
    </RelativeLayout>


    That’s it. Same as SignUpActivity.


    If “Login” button is clicked, One new activity LogOutActivity will appear .

    LogOutActivity contains a “SignOut” button .

    LogOutActivity.java:

    public class LogoutActivity extends AppCompatActivity {
    
        private Button logout;
        private FirebaseAuth auth;
        private ProgressDialog progressDialog;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_logout);
    
            getSupportActionBar().setTitle("Log Out");
            logout = (Button)findViewById(R.id.logout_button);
    
            auth = FirebaseAuth.getInstance();
            progressDialog = new ProgressDialog(this);
            progressDialog.setMessage("Loading...");
            progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
    
            logout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    logout();
                }
            });
    
        }
    
        private void logout(){
            progressDialog.show();
            auth.signOut();
    
            FirebaseAuth.AuthStateListener listener = new FirebaseAuth.AuthStateListener(){
                @Override
                public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
                    progressDialog.dismiss();
                    if(firebaseAuth.getCurrentUser() == null){
                        //logout successful
                        AlertDialog.Builder builder = new AlertDialog.Builder(LogoutActivity.this, R.style.DialogStyle);
                        builder.setMessage("Logout successful !!");
                        builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                finish();
                            }
                        });
                        builder.show();
                    }else{
                        AlertDialog.Builder builder = new AlertDialog.Builder(LogoutActivity.this, R.style.DialogStyle);
                        builder.setMessage("Oops..please try again !!");
                        builder.setPositiveButton("OK", null);
                        builder.show();
                    }
                }
            };
            auth.addAuthStateListener(listener);
        }
    }
    

     activity_logout.xml

    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout 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:id="@+id/activity_logout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context="com.codevscolor.firebasedemo.account.LogoutActivity">
    
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:background="@color/buttoncolor"
            android:text="Log out"
            android:textColor="@color/textColor"
            android:id="@+id/logout_button" />
    </RelativeLayout>
    

    That’s it. Source code is shared on Github. If you love this tutorial, don’t forget to subscribe to our newsletter for new updates.

 

Firebase using Android Studio : Part 1 : Introduction

“Firebase” is a backend platform that helps you to create a cross-platform application without having much server side knowledge. In this tutorial series, we will learn how to use it with android and what are the different features it offers.

Register a new Project :

Open https://console.firebase.google.com
1. Login using your Google Account . Click on “Create New Project”

firebase in android tutorial

 

 

 

 

2. Give one new name of your project , select one “Country/Region” and click “Create Project”

firebase in android tutorial

 

 

 

 

 

 

 

 

 

 

3. You will be forwarded to your dashboard. Click on “Add Firebase to your android app”

firebase in android tutorial

 

 

 

 

 

4. Enter your application package name (in my case it is com.codevscolor.firebasedemo) and click “Add App”

firebase in android tutorial

 

 

 

 

 

 

 

 

 

 
5. It will prompt you to download one “google-services.json” file. Save it .

6. Click “Continue” -> “Finish”

7. Click on “Auth” -> Click on “Sign-In Method” -> “Email/Password” and set it enabled.

firebase in android tutorial firebase in android

 

 

 

 

 

 

 

8. Save it.

Bingo….you have created your first project 🙂 On Next tutorial we will learn how to add firebase to your Android Application.