Firebase database Authentication in Android

In the last article we have learned about the Firebase Analytics and Firebase Crashlytics
Firebase also provides awesome feature about real time Database. It is a powerful platform for building iOS, Android, and web-based apps, offering real-time data storage and synchronization, user authentication, and more.

Store and sync data with our NoSQL cloud database. Data is synced across all clients in realtime, and remains available when your app goes offline. No server required to configure and no any API call required like using volley and Retrofit.

It is very easy to use. Firebase still in Beta So here you can get started.



Lets start configuration for firebase database and firebase authentication.

Step.1: Please go to Firebase console to create the project.

Step.2: Now you can create the project name and enter your county name. 

Step.3: You have to choose which platform do you want to use firebase push. Here we are configuring for android platform, so I am choosing option for android app. 

Step.4: Now you need to enter your package name of your project. Ex: Here my package name is "com.sunil.firebasedatabasetest" . Other fields are optional for debug mode. But if you want to release your app that time you need to pass the SHA-1 key. 



Step.5: Once you done your step.5 You will get downloded one google-services.json file. You have to copy this file and paste inside the app folder. 

Wow You have done your configuration. Now add your dependencies in your project level and app level.

build.gradle project level

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.2.2'
        classpath 'com.google.gms:google-services:3.0.0'
        classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files

    }
}

allprojects {
    repositories {
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}


build.gradle app level

apply plugin: 'com.android.application'
apply plugin: 'com.neenbedankt.android-apt'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.0"
    defaultConfig {
        applicationId "com.sunil.firebasedatabasetest"
        minSdkVersion 15
        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'])
    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:25.0.0'
    testCompile 'junit:junit:4.12'

    compile 'com.firebaseui:firebase-ui-database:0.6.2'
    compile 'com.google.firebase:firebase-auth:9.8.0'
    compile 'com.google.firebase:firebase-database:9.8.0'

    compile 'com.android.support:recyclerview-v7:25.0.0'
    compile 'com.android.support:cardview-v7:25.0.0'
    compile 'com.android.support:design:25.0.0'

    compile 'com.jakewharton:butterknife:8.4.0'
    apt 'com.jakewharton:butterknife-compiler:8.4.0'

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


Lets create the signup and sign by using Firebase Auth.




Now I am sharing the core part of code that required to signup with firebase auth.Before make sure you have enabled the Email from console.

SignUpFragment.java

  @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        rootView = inflater.inflate(R.layout.fragment_signup, container, false);
        ButterKnife.bind(this, rootView);

        // Initialize FirebaseAuth
        mFirebaseAuth = FirebaseAuth.getInstance();

        return rootView;
    }

 @OnClick(R.id.SignUp)
    public void onClickSignUp(){
        if (!valid()){
            return;
        }else {

            String email = emailEditText.getText().toString().trim();
            String password = passwordEditText.getText().toString().trim();
            mFirebaseAuth.createUserWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener() {
                @Override
                public void onComplete(@NonNull Task task) {
                    if (task.isSuccessful()){
                      mListener.onSignUpDone();
                    }else{
                        Utility.showDialog(getActivity(), task);
                    }

                }
            });
        }
    }


Once you done signup successfully, you can see on dashboard one user entry insert.  Please refer snap shot that helps you to show the user entry.



Now you can try with login with same email and password credential.




SignInFragment.java

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Fragment;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.TextInputLayout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;

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;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.sunil.firebasedatabasetest.R;
import com.sunil.firebasedatabasetest.utils.SharedPreferenceUtils;
import com.sunil.firebasedatabasetest.utils.Utility;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;  
public class SignInFragment extends Fragment {

    public static final String TAG = SignInFragment.class.getSimpleName();
    private View rootView;

    OnFragmentInteractionListener mListener;
    private FirebaseAuth mFirebaseAuth;

    @BindView(R.id.emailLayout)
    TextInputLayout emailLayout;
    @BindView(R.id.passwordLayout)
    TextInputLayout passwordLayout;

    @BindView(R.id.email)
    EditText emailEditText;
    @BindView(R.id.password)
    EditText passwordEditText;


    public static SignInFragment newInstance() {
        SignInFragment fragment = new SignInFragment();
        return fragment;
    }

    public SignInFragment() {
        // Required MyFundsCategoriesFragment public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {

        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        rootView = inflater.inflate(R.layout.fragment_signin, container, false);
        ButterKnife.bind(this, rootView);

        // Initialize FirebaseAuth
        mFirebaseAuth = FirebaseAuth.getInstance();

        return rootView;
    }

    @TargetApi(23)
    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        onAttachToContext(context);
    }

    /*
     * Deprecated on API 23
     * Use onAttachToContext instead
     */


    @SuppressWarnings("deprecation")
    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            onAttachToContext(activity);
        }
    }

    /*
     * Called when the fragment attaches to the activity
     */
    protected void onAttachToContext(Context context) {
        Activity activity = (Activity) context;
        try {
            mListener = (OnFragmentInteractionListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    public interface OnFragmentInteractionListener {
        void onSignInDone();
    }

    @OnClick(R.id.signIn)
    public void getSignInClick(){
        if (!valid()){
            return;
        }else {
            String email = emailEditText.getText().toString().trim();
            String password = passwordEditText.getText().toString().trim();

            mFirebaseAuth.signInWithEmailAndPassword(email, password)
                    .addOnCompleteListener(getActivity(), new OnCompleteListener() {
                        @Override
                        public void onComplete(@NonNull Task task) {
                            if (task.isSuccessful()){
                                FirebaseUser user = task.getResult().getUser();
                                Log.d(TAG, "onComplete: uid=" + user.getUid());
                                SharedPreferenceUtils.getInstance(getActivity()).setUUID(user.getUid());
                                SharedPreferenceUtils.getInstance(getActivity()).setEmail(user.getEmail());
                                mListener.onSignInDone();
                            }else{
                                Utility.showDialog(getActivity(), task);
                            }

                        }
                    });
        }
    }

    private boolean valid(){
        boolean isValid;
        if (!Utility.validateEmail(emailLayout)){
            isValid = false;
        }
        else if (Utility.nullCheck(passwordLayout, "Password")){
            isValid = false;
        }else{
            isValid = true;
        }
        return  isValid;
    }
}


Now you are logged user. Lets create the database with notes table. Every user can add notes. Lets show all created notes in recyclerView. And add note with title and description.
Lets checkout first create a note.



AddNoteFragment.java

import android.app.Activity;
import android.app.Fragment;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.support.design.widget.TextInputLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;

import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
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.Query;
import com.google.firebase.database.ValueEventListener;
import com.sunil.firebasedatabasetest.adapter.NoteAdapter;
import com.sunil.firebasedatabasetest.model.NotesModel;
import com.sunil.firebasedatabasetest.R;
import com.sunil.firebasedatabasetest.utils.SharedPreferenceUtils;
import com.sunil.firebasedatabasetest.utils.Utility;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by sunil on 11/7/16.
 */

public class AddNoteFragment extends Fragment{

    public static final String TAG = AddNoteFragment.class.getSimpleName();
    private View rootView;

    OnFragmentInteractionListener mListener;
    DatabaseReference myRef;
    DatabaseReference database;
    private FirebaseAuth mFirebaseAuth;

    @BindView(R.id.titleLayout)
    TextInputLayout titleLayout;
    @BindView(R.id.discriptionLayout)
    TextInputLayout descriptionLayout;

    @BindView(R.id.title)
    EditText titleEditText;
    @BindView(R.id.discription)
    EditText descriptionEditText;

    public static AddNoteFragment newInstance() {
        AddNoteFragment fragment = new AddNoteFragment();
        return fragment;
    }

    public AddNoteFragment() {
        // Required MyFundsCategoriesFragment public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {

        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        rootView = inflater.inflate(R.layout.fragment_add_note, container, false);
        ButterKnife.bind(this, rootView);

        database = FirebaseDatabase.getInstance().getReference();

        return rootView;
    }

    @TargetApi(23)
    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        onAttachToContext(context);
    }

    /*
     * Deprecated on API 23
     * Use onAttachToContext instead
     */


    @SuppressWarnings("deprecation")
    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            onAttachToContext(activity);
        }
    }

    /*
     * Called when the fragment attaches to the activity
     */
    protected void onAttachToContext(Context context) {
        Activity activity = (Activity) context;
        try {
            mListener = (OnFragmentInteractionListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    public interface OnFragmentInteractionListener {
        void notesAddedDone();
    }

    @OnClick(R.id.addNote)
    public void onClickAddNote(){
        if (!valid()){
            return;
        }else {

            String title = titleEditText.getText().toString().trim();
            String description = descriptionEditText.getText().toString().trim();
            addNotes(title, description);
        }
    }

    private void addNotes(final String title, final String description){
        final String userId = SharedPreferenceUtils.getInstance(getActivity()).getUUID();
        final String userEmail = SharedPreferenceUtils.getInstance(getActivity()).getEmail();
        //NotesModel model = new NotesModel(userEmail, userId,title, description);
       // database.child("notes").setValue(model);
        database.child("notes").child(userId).addListenerForSingleValueEvent(
                new ValueEventListener() {
                    @Override
                    public void onDataChange(DataSnapshot dataSnapshot) {
                        // Get note value
                        writeNewNote(userId, userEmail, title, description);

                    }

                    @Override
                    public void onCancelled(DatabaseError databaseError) {
                        Log.w(TAG, "getUser:onCancelled", databaseError.toException());
                    }
                });
    }

    private void writeNewNote(String userId, String username, String title, String description) {
        // Create new post at /user-posts/$userid/$postid and at
        // /posts/$postid simultaneously
        String key = database.child("notes").push().getKey();
        NotesModel notesModel = new NotesModel(username,userId, title, description);
        Map postValues = notesModel.toMap();

        Map childUpdates = new HashMap<>();
        childUpdates.put("/notes/" + key, postValues);

        database.updateChildren(childUpdates);

        mListener.notesAddedDone();
    }

    private boolean valid(){
        boolean isValid;
        if (Utility.nullCheck(titleLayout, "Title")){
            isValid = false;
        }
        else if (Utility.nullCheck(descriptionLayout, "Description")){
            isValid = false;
        }
        else{
            isValid = true;
        }
        return  isValid;
    }
}


Now what we had added notes by users we can show on recyclerview. Here is sample code.


UserNotesFragment.java

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Fragment;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
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.Query;
import com.google.firebase.database.ValueEventListener;
import com.sunil.firebasedatabasetest.R;
import com.sunil.firebasedatabasetest.adapter.NoteAdapter;
import com.sunil.firebasedatabasetest.model.NotesModel;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by sunil on 11/10/16.
 */

public class UserNotesFragment extends Fragment {

        public static String TAG = UserNotesFragment.class.getSimpleName();
        private View rootView;

        @BindView(R.id.recycler_view)
        RecyclerView mRecyclerView;

        OnFragmentInteractionListener mListener;
        DatabaseReference database;
        private FirebaseAuth mFirebaseAuth;
        FirebaseUser mFirebaseUser;
        private String mUserId;

        public static UserNotesFragment newInstance() {
            UserNotesFragment fragment = new UserNotesFragment();
            return fragment;
        }

        public UserNotesFragment() {
            // Required MyFundsCategoriesFragment public constructor
        }

        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            if (getArguments() != null) {

            }
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            // Inflate the layout for this fragment
            rootView = inflater.inflate(R.layout.fragment_userlist, container, false);
            ButterKnife.bind(this, rootView);

            database = FirebaseDatabase.getInstance().getReference();
            // Initialize FirebaseAuth
            mFirebaseAuth = FirebaseAuth.getInstance();

            mFirebaseUser = mFirebaseAuth.getCurrentUser();

            if (mFirebaseUser != null) {
                mUserId = mFirebaseUser.getUid();

            }

            LinearLayoutManager mManager = new LinearLayoutManager(getActivity());
            mManager.setReverseLayout(true);
            mManager.setStackFromEnd(true);
            mRecyclerView.setLayoutManager(mManager);
            mRecyclerView.setHasFixedSize(true);

            DatabaseReference usernameRef = database.child("notes");
            Query queryRef = usernameRef.orderByKey();
            queryRef.addListenerForSingleValueEvent(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    List notesModels = new ArrayList();
                    for (DataSnapshot child: dataSnapshot.getChildren()) {
                        String title = (String) child.child("title").getValue();
                        String description = (String) child.child("description").getValue();
                        String user = (String) child.child("user").getValue();
                        NotesModel notesModel = new NotesModel();
                        notesModel.setDescription(description);
                        notesModel.setUser(user);
                        notesModel.setTitle(title);
                        notesModels.add(notesModel);

                    }

                    NoteAdapter adapter = new NoteAdapter(getActivity(), notesModels);
                    mRecyclerView.setAdapter(adapter);
                }

                @Override
                public void onCancelled(DatabaseError databaseError) {
                    Log.e(TAG, databaseError.getMessage());
                }
            });

            return rootView;
        }

        @TargetApi(23)
        @Override
        public void onAttach(Context context) {
            super.onAttach(context);
            onAttachToContext(context);
        }

        /*
         * Deprecated on API 23
         * Use onAttachToContext instead
         */


        @SuppressWarnings("deprecation")
        @Override
        public void onAttach(Activity activity) {
            super.onAttach(activity);
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
                onAttachToContext(activity);
            }
        }

        /*
         * Called when the fragment attaches to the activity
         */
        protected void onAttachToContext(Context context) {
            Activity activity = (Activity) context;
            try {
                mListener = (OnFragmentInteractionListener) activity;
            } catch (ClassCastException e) {
                throw new ClassCastException(activity.toString()
                        + " must implement OnFragmentInteractionListener");
            }
        }

        @Override
        public void onDetach() {
            super.onDetach();
            mListener = null;
        }


        public interface OnFragmentInteractionListener {
            void addNoteClick();
        }

        @OnClick(R.id.create)
        public void addNoteClick(){
            mListener.addNoteClick();
        }

}

Lets check the database and tables what inserted data. Please go to your project dash board and click of menu option database. Here are my database details.



Thanks for reading this post. I hope it will help you to create the firebase real time database.

No comments:

Post a Comment

Debug Database in Android

In my last tutorial, we have learned how we can use persistence database in android. We also understood which database wrapper we can use...

Contact Me

Name

Email *

Message *