Firebase Authentication Demo In Java

Shradha Rathod
9 min readJun 6, 2021

Firebase is Google’s mobile application development platform which helps developers to focus on crafting fantastic user experiences efficiently.

as,

  • You don’t need to manage servers.
  • You don’t need to write APIs. Firebase is your server, your API, and your datastore, all written so generically that you can modify it to suit most needs.
  • Firebase can’t be everything to everybody. But it gets pretty close.
  • It is built on Google’s infrastructure.
  • Firebase is categorized as a NoSQL database program, which stores data in JSON-like documents.

Firebase furnishes developers with the following tools and services to help them develop quality apps, grow their user base, and earn profit.

  1. Authentication: It is used to authenticate the users of your applications.
  2. Realtime Database: It is used to store and retrieve data in real-time.
  3. Google Analytics: It will generate a report of your application. For example, a report of users increased in the last one month or active users, etc.
  4. Cloud Firestore: It is a NoSQL database that is used to easily store, sync, and query data for applications.
  5. Crashlytics: It provides you with the crash reports of your application.
  6. Test Labs: It will test your applications on the devices hosted by Google.
  7. Performance Monitoring: Monitors the performance of your application every second.
  8. In-App Messaging: It helps you to send in-app messages that help your users to interact with you.
  9. ML Kit: It gives the power of Machine Learning to your applications.
  10. Remote Config: It helps you change or add some features to your app without any updates.

Apart from the above-mentioned products of Firebase, some of the other Firebase products are Cloud Functions, Hosting, Cloud Storage, App Distribution, Predictions, A/B Testing, Cloud Messaging, and Dynamic Links.

In this demo, We will see about the authentication part of Firebase.

So, How does it work?

In Authentication we sign a user into our app, we first get authentication credentials from the user. These credentials can be the user’s email address and password. Then, we pass these credentials to the Firebase Authentication SDK. Then the Firebase backend services will verify those credentials and return a response to the client.

Firebase supports authentication using email and password, phone numbers, or even you can use Facebook, Google, Twitter, GitHub, etc.

Now, let’s understand how to make authentication with firebase in our mobile application.

Example of user Sign In and Sign Up :

In this example, we are using four activities,

  • SignUpActivity (For user sign up)
  • SignInActivity (For user sign in)
  • ForgetPasswordActivity(For resetting user password)
  • WelcomeActivity(Welcome text and sign out option)

To use Firebase Authentication in our application, we need to connect our project i.e. the Android Studio project to Firebase. Following are the steps that are used to connect an Android project to Firebase:

Step 1: Open Android Studio and create a new project or open an existing project.

Step 2: Open the Firebase Website and sign in into it. (use the same email id as used in Android Studio for sign in)

Step 3: After sign in, click on the “Go To Console” button that is present on the upper right side of the website.

Step 4: Click on “Add Project”.

Step 5: Enter the project name you are creating and click on continue. (here project name Auth)

Step 6: After this, you will able to see the below screen. Now you have to enable ‘Google Analytics for this project’ and again click on the continue button.

Step 7: Select account as default account firebase and click on create the project.

Step 8: Now your project will be created, it will take a while and then you see your new project is ready.

Step 9: After creating a project, click on continue and you will see the below image of your project dashboard.

Now on the left side of the image, you can see here, all the services of Firebase are shown and you can use any of them.

Step 10: In this example, first of all, we are interested in the authentication part, so click on the “Authentication” and then click on Get started.

And then switch to the “Sign-in method” tab.

Step 11: In our example, we will sign in by email. So, click on the edit button next to the “Email/Password” option and you will see the below screen. and click on “Save”. You are done with the Firebase website part

Step 12: Come back to your project in Android Studio and click on Tools > Firebase > Authentication. And you will see the screen below.

Step 13: We are almost done, now we have to add our project in Android Studio with the project that we have created in the Firebase. So, click on “Authenticate using Google Sign-in “. Here, we are having two options i.e. “Connect to Firebase” and “Add the Firebase Authentication SDK to your app. Firstly, we have to connect our project to Firebase, so, click on the “Connect to Firebase” button.

Step14: Now you have to select the project that you have created earlier on Firebase and then click on “Connect to Firebase’’

Now, you can see the screen below.

Step 15: Now, your project on the Android Studio is connected with the one present on the Firebase and you will see the below screen which informs you “Your Android Studio Project is connected to Firebase Android app”

Step 16:Lastly, we have to add some dependencies to our projects. So, click on “Add the Firebase Authentication SDK to your app”(this is the second option that we found on step number 12). A dialog box will be opened. Click on “Accept Changes” and it will automatically add all the dependencies to your project.

Phew! Finally, we are done with all the steps that are required to connect our Android Studio project with Firebase for Authentication. Now, let’s move on to the coding part.

As discussed earlier, in our example, we will be having four activities:

  • SignUpActivity (For user sign up)

This activity is used to sign up the user into the application and after successful Sign Up, transfer the user to the SignInActivity. It contains two EditText for taking email and password from the user for registration.

  • SignInActivity (For user sign in)

This activity is used to sign in the user into the application. It contains two EditText for taking email and password from the user. Two buttons for Login(sign in)and Signup(signup button will transfer the user to the SignupActivity) and one TextView (ForgotPassword)that will transfer the user to the ForgotPasswordActivity.

  • ForgetPassword Activity(For resetting user password)

This activity is used to send the forgot password link to the user to set a new password. The reset link will be sent to the user’s email id.

  • WelcomeActivity(Welcome Text and Sign Out Option)

This activity is used to display welcome text and have option to sign out from Firebase account.

Sign Up a user with email and password

To sign up a user with an email and password, firstly, you have to declare an instance of FirebaseAuth.

FirebaseAuth auth;

Now, in the onCreate() method, initialize the FirebaseAuth

auth = FirebaseAuth.getInstance();

To sign up a user with an email and password, we can take the help of the createUserWithEmailAndPassword() method. This method takes email and password as a parameter, validates them, and then creates a new user.

auth.createUserWithEmailAndPassword(editEmail.getText().toString(),
editPassword.getText().toString()).addOnCompleteListener(task -> {
if (task.isSuccessful()) {
startActivity(new Intent(SignUpActivity.this, MainActivity.class));
Toast.makeText(SignUpActivity.this, getString(R.string.user_sign_up_success), Toast.LENGTH_LONG).show();
finish();
} else {
Toast.makeText(SignUpActivity.this, getString(R.string.try_again), Toast.LENGTH_LONG).show();
}
}).addOnFailureListener(e -> Toast.makeText(SignUpActivity.this, e.getLocalizedMessage(), Toast.LENGTH_LONG).show());

You can find the full code of activity_sign_up.xml from here and SignUpActivity.java from here.

That’s it. Your user will be registered and you can see the registered user on the Firebase website under the Authentication section and then in the Users tab. If you are trying to sign up with the same email more than once, then you will receive an error or in simple words your task is unsuccessful.

Sign In a user with email and password

In the previous section, we saw how to sign up a user with an email and password. Now, we need to sign in the user by authenticating the email and password entered by the user.

If the user Sign In successfully then he will receive an email as “Verify your email for the project” then you have to click on it for verification.

Now, declare an instance of FirebaseAuth as we did in SignUpActivity.

FirebaseAuth auth;

And then instantiate it in the onCreate method

auth = FirebaseAuth.getInstance();

To Sign In a user with an email and password, we have one method called signInWithEmailAndPassword(). This method takes email and password as a parameter, validates them, and then sign in as a user in your application if the validation is successful. Following is the code for the same:

auth.signInWithEmailAndPassword(editEmailAddress.getText().toString(),
editPassWord.getText().toString()).addOnCompleteListener(MainActivity.this, task -> {
if (task.isSuccessful()) {
FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
if (Objects.requireNonNull(firebaseUser).isEmailVerified()) {
startActivity(new Intent(MainActivity.this, WelcomeActivity.class));
finish();
Toast.makeText(MainActivity.this, getString(R.string.log_in_success), Toast.LENGTH_SHORT).show();
} else {
firebaseUser.sendEmailVerification();
Toast.makeText(MainActivity.this, getString(R.string.please_check_email), Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(MainActivity.this, getString(R.string.log_in_failed), Toast.LENGTH_SHORT).show();
}
});

You can find the full code of activity_sign_in.xml from here and SignInActivity.java from here.

Check if a user is already Sign In

We can use the getCurrentUser() method to get the status of a user. If yes, then send the user directly in ‘WelcomeActivity’.

if (auth.getCurrentUser() != null) {
startActivity(new Intent(this, WelcomeActivity.class));
finish();
}

Send the change password link to the email

Sometimes, the user forgot his/her password and in that case, your application should provide some way of password reset. Things become easier when you use Firebase. In Firebase, with the help of the sendPasswordResetEmail() method, you can send the password reset link to the user and by clicking on that link, the user can set the newer password.

Firstly, create an instance of FirebaseAuth.

FirebaseAuth auth;

Now, in the onCreate() method, initialize the FirebaseAuth instance.

auth = FirebaseAuth.getInstance();

After that, you can use the sendPasswordResetEmail() to send the reset email to the user. This method takes email as a parameter.

auth.sendPasswordResetEmail(email).addOnCompleteListener(ForgetPasswordActivity.this, task -> {
if (task.isSuccessful()) {
Toast.makeText(ForgetPasswordActivity.this, getString(R.string.check_your_email_reset), Toast.LENGTH_LONG).show();
} else {
Toast.makeText(ForgetPasswordActivity.this, getString(R.string.try_again), Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(this, e ->
Toast.makeText(
ForgetPasswordActivity.this,
e.getLocalizedMessage(),
Toast.LENGTH_SHORT).show()
);

You can find the full code of activity_forget_password.xml from here and ForgetPasswordActivity.java from here.

Pros and cons of using Firebase

Some of the advantages of using Firebase are:

  • Quick and easy integration and setup
  • So many functions are available for performing complex operations.
  • Realtime update.
  • No configuration is required on the server-side.

Some of the disadvantages of using Firebase are:

  • The storage format is NoSQL. It uses JSON format.
  • While performing authentication, you need to make sure that the user logged in to the app should not have access to the database.

Screenshots :

--

--