Firebase User Authentication in android

Sharing is caring!

Firebase authentication in Android is one of the best features to connect users with your application. Firebase is actually cloud that provides the backend. Firebase has own API for communication for example signup and login. So today in this tutorial we will learn how to create a sign-up and sign-in for the user by using Firebase API.

Firebase actually stores the user credential securely in their system while signup did by users and while trying to login it will validate the user credential which is entered at the time of registration. So in this case developer will not worry about to storing the user data on the server and authenticate those.  You can replicate your idea into building the awesome android app even though you do not have server and API.

Ok, Let’s see how to create the register and login with Firebase Authentication in Android. You have followed few simple steps to do configuration on Firebase console. Here are steps:

  1. Please go to Firebase console to create the project. Here you can pass the project name and enter your country name etc.
  2. You have to choose which platform do you want to use. Here we are configuring for Android platform, so I am choosing an option for Android app.
  3. 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.
  4. Once you have done your step.4 You will get downloaded one google-services.json file. You have to copy this file and paste inside the app folder.

Great done well so far. Now you need to add Firebase dependencies in your Gradle file.

compile 'com.google.firebase:firebase-auth:11.0.2'
compile 'com.google.android.gms:play-services-auth:11.0.2'

Now I need to create the signup page for the user registration. Here I created SignUpFragment for the user registration. In this fragment, you need to initialize FirebaseAuth to get the instance of FirebaseAuth. 

  @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;
    }

Once you have the Firebase instance then you required to enter the user email and password to Firebase API to create a user for your application.

 @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<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                    if (task.isSuccessful()){
                      mListener.onSignUpDone();
                    }else{
                        Utility.showDialog(getActivity(), task);
                    }

                }
            });
        }
    }

Here you will get the response of Firebase for created the user Object. If the object having status success then it means Firebase API have created the user successfully else you can check the error status.

Now let’s create the login page for authenticating the user credential by using Firebase login API. Here I am creating the login page of SignInFragment.

 @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;
    }

Again you have to get first Firebase authentication instance for validation the user credential by Firebase API. Once you had firebase auth instance then call the Firebase API to validate user email and password.

 @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<AuthResult>() {
                        @Override
                        public void onComplete(@NonNull Task<AuthResult> 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);
                            }

                        }
                    });
        }
    }

Here you will get the response of Firebase for authenticating the user Object. If the object having status success then it means Firebase API have authenticated user credential successfully else you can check the error status.

Wrapping Up: As we have seen that Firebase is awesome for instant building the app. Even if you do not have any backend ready till now then you can use the Firebase cloud for a backend to quick start your idea into the Android application. If you want to upload user profile while registering the user then Firebase provides the cloud storage to upload the file or image. Please check this post to upload a file on Firebase Storage in android.

Here you can get access the GitHub source code for Firebase.

Please do subscribe email to get all newsletters of this blog and if you feel that this post will help you to understand then do not forget to subscribe, share and comment below.

Happy Coding 🙂

0 0 votes
Article Rating
Firebase User Authentication in android
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Akhil

thanks a ton …helped me alot in my android project.Cleared some doubts which am not getting in other platforms.Make more blogs like this.

Scroll to top
1
0
Would love your thoughts, please comment.x
()
x