Firebase Email Authentication Android Studio

Firebase Email Authentication Android Studio

This article describes how to create Firebase email authentication in android studio. if it is the first time to see Firebase tutorials, The article in this link describes how to connect android studio project to Firebase.

Many apps require to know the identity of the user. More over, you need to securely save users data. Firebase email authentication allows users to sign up with their email and password. So that, I will describe step by step how to add Email and password authentication to your app.

In the previous article I described how to link your android studio project to Firebase using Firebase services Plugin. In this article “Firebase Email Authentication Android Studio” we will complete the authentication part considering that you have created android studio project and the project already connected to the Firebase and you able to use Firebase assistant in android studio. So, Open Tools menu in android studio and select Firebase. You will see Firebase assistant as the following image.

firebase assistant

Good job, now click “Authentication” then click “Email and password Authentication” link in Firebase assistant.

add firebase email and password authentication

You should see that first step done and your project connected. Then click on “Add Firebase Authentication to your app” Button as shown in the above image. The next dialog will appear to perform an action of adding google services and Firebase Authentication dependencies, click “Accept Changes” button and wait until project sync finished.

dependencies for firebase authentication

Next, Open Firebase console and go to your project Firebase app and click on “Authentication” then “Sign in Methods” tab. Then, click on Email/Password to enable this sign in method. Enable the two options appear for and click save. Now your app is ready to create user registration and login.

enable email and password sign in method

Create Login and Registration XML layouts

Firstly, we need to create login and registration XML layouts. So, Open Main Activity XML layout resource file. Then, add the following XML code for login form and login and register buttons.

<?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:layout_width="match_parent"
 android:layout_height="match_parent"
 android:background="@color/colorPrimaryDark"
 tools:context=".MainActivity">

<LinearLayout
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:orientation="vertical"
 android:layout_centerVertical="true"
 >
<TextView
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:gravity="center"
 android:text="Login"
 android:textSize="50sp"
 android:textStyle="bold"
 android:layout_marginTop="10dp"
 android:textColor="@color/colorPrimary"
 />
<FrameLayout
 android:layout_width="match_parent"
 android:layout_height="60dp"
 android:layout_margin="20dp"
 android:elevation="10dp"
 android:outlineAmbientShadowColor="@android:color/darker_gray"
 android:background="@drawable/white_boarder"
 tools:targetApi="p">
<com.rengwuxian.materialedittext.MaterialEditText
 android:id="@+id/email"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:layout_gravity="center_horizontal"
 app:met_floatingLabel="normal"
 android:hint="Email Address"
 android:paddingLeft="16dp"
 android:paddingRight="16dp"
 app:met_baseColor="@color/colorPrimaryDark"
 android:backgroundTint="@color/colorPrimaryDark"
 android:textColorHint="@color/colorPrimaryDark"
 android:textStyle="bold"
 android:inputType="textEmailAddress"
 app:met_textColor="@color/colorPrimaryDark"
 />

</FrameLayout>

<FrameLayout
 android:layout_width="match_parent"
 android:layout_height="60dp"
 android:layout_margin="20dp"
 android:elevation="10dp"
 android:outlineAmbientShadowColor="@android:color/darker_gray"
 android:background="@drawable/white_boarder"
 tools:targetApi="p">
<com.rengwuxian.materialedittext.MaterialEditText
 android:id="@+id/password"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:layout_gravity="center_horizontal"
 app:met_floatingLabel="normal"
 android:hint="Password"
 android:paddingLeft="16dp"
 android:paddingRight="16dp"
 app:met_baseColor="@color/colorPrimaryDark"
 android:backgroundTint="@color/colorPrimaryDark"
 android:textColorHint="@color/colorPrimaryDark"
 android:textStyle="bold"
 android:inputType="textPassword"
 app:met_textColor="@color/colorPrimaryDark"
 />
</FrameLayout>

<ProgressBar
 android:layout_width="60dp"
 android:layout_height="60dp"
 android:id="@+id/progressBar"
 android:layout_gravity="center"
 android:indeterminateTint="@color/colorPrimary"
 tools:targetApi="lollipop"
 android:visibility="gone"/>

<FrameLayout
 android:layout_width="match_parent"
 android:layout_height="50dp"
 android:layout_marginTop="20dp"
 android:layout_marginLeft="50dp"
 android:layout_marginRight="50dp"
 android:elevation="10dp"
 android:outlineAmbientShadowColor="@android:color/darker_gray"
 android:background="@drawable/white_boarder"
 tools:targetApi="p">
<Button
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:text="Login"
 android:textColor="@color/colorPrimaryDark"
 android:textAllCaps="false"
 android:id="@+id/login"
 android:textSize="20sp"
 android:background="?attr/selectableItemBackground"/>
</FrameLayout>

<FrameLayout
 android:layout_width="match_parent"
 android:layout_height="50dp"
 android:layout_marginTop="20dp"
 android:layout_marginLeft="50dp"
 android:layout_marginRight="50dp"
 android:elevation="10dp"
 android:outlineAmbientShadowColor="@android:color/darker_gray"
 android:background="@drawable/white_boarder"
 tools:targetApi="p">
<Button
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:text="Register"
 android:textColor="@color/colorPrimaryDark"
 android:textAllCaps="false"
 android:id="@+id/register"
 android:textSize="20sp"
 android:background="?attr/selectableItemBackground"/>
</FrameLayout>
<TextView
 android:layout_width="wrap_content"
 android:layout_height="match_parent"
 android:id="@+id/forget"
 android:text="Forget password?"
 android:layout_margin="20sp"
 android:layout_gravity="center"
 android:textSize="20sp"
 android:textStyle="bold"
 android:textColor="@color/colorPrimary"
 android:linksClickable="true"/>


</LinearLayout>


</RelativeLayout>

Then, Create a new activity and name it Register Activity. After that add the following XML code in the register activity XML layout resource file.

<?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:layout_width="match_parent"
 android:layout_height="match_parent"
 tools:context=".RegisterActivity">
<include
 android:id="@+id/toolbar"
 layout = "@layout/bar_layout"/>
<ScrollView
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:layout_below="@+id/toolbar">
<RelativeLayout
 android:layout_width="match_parent"
 android:layout_height="wrap_content">
<LinearLayout
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:orientation="vertical"
 >
<TextView
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:layout_marginTop="10dp"
 android:text="Create New Account"
 android:gravity="center"
 android:textColor="@color/colorPrimaryDark"
 android:textSize="30sp"
 android:textStyle="bold"/>

<FrameLayout
 android:layout_width="match_parent"
 android:layout_height="60dp"
 android:layout_margin="20dp"
 android:elevation="10dp"
 android:outlineAmbientShadowColor="@android:color/darker_gray"
 android:background="@drawable/white_boarder"
 tools:targetApi="p">
<com.rengwuxian.materialedittext.MaterialEditText
 android:id="@+id/username"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:layout_gravity="center_horizontal"
 app:met_floatingLabel="normal"
 android:hint="User Name"
 android:paddingLeft="16dp"
 android:paddingRight="16dp"
 app:met_baseColor="@color/colorPrimaryDark"
 android:backgroundTint="@color/colorPrimaryDark"
 android:textColorHint="@color/colorPrimaryDark"
 android:textStyle="bold"
 android:inputType="textPersonName"
 app:met_textColor="@color/colorPrimaryDark"
 />

</FrameLayout>

<FrameLayout
 android:layout_width="match_parent"
 android:layout_height="60dp"
 android:layout_margin="20dp"
 android:elevation="10dp"
 android:outlineAmbientShadowColor="@android:color/darker_gray"
 android:background="@drawable/white_boarder"
 tools:targetApi="p">
<com.rengwuxian.materialedittext.MaterialEditText
 android:id="@+id/email"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:layout_gravity="center_horizontal"
 app:met_floatingLabel="normal"
 android:hint="Email Address"
 android:paddingLeft="16dp"
 android:paddingRight="16dp"
 app:met_baseColor="@color/colorPrimaryDark"
 android:backgroundTint="@color/colorPrimaryDark"
 android:textColorHint="@color/colorPrimaryDark"
 android:textStyle="bold"
 android:inputType="textEmailAddress"
 app:met_textColor="@color/colorPrimaryDark"
 />

</FrameLayout>

<FrameLayout
 android:layout_width="match_parent"
 android:layout_height="60dp"
 android:layout_margin="20dp"
 android:elevation="10dp"
 android:outlineAmbientShadowColor="@android:color/darker_gray"
 android:background="@drawable/white_boarder"
 tools:targetApi="p">
<com.rengwuxian.materialedittext.MaterialEditText
 android:id="@+id/password"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:layout_gravity="center_horizontal"
 app:met_floatingLabel="normal"
 android:hint="Password"
 android:paddingLeft="16dp"
 android:paddingRight="16dp"
 app:met_baseColor="@color/colorPrimaryDark"
 android:backgroundTint="@color/colorPrimaryDark"
 android:textColorHint="@color/colorPrimaryDark"
 android:textStyle="bold"
 android:inputType="textPassword"
 app:met_textColor="@color/colorPrimaryDark"
 />

</FrameLayout>

<FrameLayout
 android:layout_width="match_parent"
 android:layout_height="60dp"
 android:layout_margin="20dp"
 android:elevation="10dp"
 android:outlineAmbientShadowColor="@android:color/darker_gray"
 android:background="@drawable/white_boarder"
 tools:targetApi="p">
<com.rengwuxian.materialedittext.MaterialEditText
 android:id="@+id/mobile"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:layout_gravity="center_horizontal"
 app:met_floatingLabel="normal"
 android:hint="Mobile"
 android:paddingLeft="16dp"
 android:paddingRight="16dp"
 app:met_baseColor="@color/colorPrimaryDark"
 android:backgroundTint="@color/colorPrimaryDark"
 android:textColorHint="@color/colorPrimaryDark"
 android:textStyle="bold"
 android:inputType="textPhonetic"
 app:met_textColor="@color/colorPrimaryDark"
 />

</FrameLayout>
<RadioGroup
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:orientation="vertical"
 android:layout_margin="20dp"
 android:padding="10dp"
 android:background="@drawable/orange_boarder"
 android:id="@+id/radioButton">
<RadioButton
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:textStyle="bold"
 android:textSize="14sp"
 android:textColor="@color/colorPrimary"
 android:text="Male"
 android:buttonTint="@color/colorPrimary"
 android:id="@+id/male"
 tools:targetApi="lollipop" />

<RadioButton
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:textStyle="bold"
 android:textSize="14sp"
 android:textColor="@color/colorPrimary"
 android:text="Female"
 android:buttonTint="@color/colorPrimary"
 android:id="@+id/female"
 tools:targetApi="lollipop" />

</RadioGroup>

<ProgressBar
 android:layout_width="60dp"
 android:layout_height="60dp"
 android:id="@+id/progressBar"
 android:layout_gravity="center"
 android:indeterminateTint="@color/colorPrimaryDark"
 tools:targetApi="lollipop"
 android:visibility="gone"/>
<FrameLayout
 android:layout_width="match_parent"
 android:layout_height="50dp"
 android:layout_marginTop="20dp"
 android:layout_marginLeft="50dp"
 android:layout_marginRight="50dp"
 android:elevation="10dp"
 android:outlineAmbientShadowColor="@android:color/darker_gray"
 android:background="@drawable/orange_boarder"
 tools:targetApi="p">
<Button
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:text="Register"
 android:textColor="@color/colorPrimary"
 android:textAllCaps="false"
 android:id="@+id/register"
 android:textSize="20sp"
 android:background="?attr/selectableItemBackground"/>
</FrameLayout>
</LinearLayout>
</RelativeLayout>
</ScrollView>


</RelativeLayout>

The next step is that we need to create activity for a successful login to show the user`s data. So, Create a new activity and name it Start Activity. More over, this activity contain Circular Image View, Bar Layout with Tool Bar, and Menu Items. You Can use the following XML Code.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:layout_width="match_parent"
 android:layout_height="match_parent"
 android:orientation="vertical"
 tools:context=".StartActivity"
 android:background="@color/colorPrimaryDark">
<include
 android:id="@+id/toolbar"
 layout="@layout/profile_bar_layout"/>
<androidx.cardview.widget.CardView
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 app:cardCornerRadius="50dp"
 android:layout_marginBottom="-40dp">

</androidx.cardview.widget.CardView>

</LinearLayout>

Add Login and Registration Authentication Methods

Secondly, We need to add methods that handle login and registration. Open mainactivity.java file and create general object of it`s XML file widgets. You can use the following.

private MaterialEditText email,password;
private ProgressBar progressBar;
private TextView forgetPassword;
private FirebaseAuth firebaseAuth;

Then in onCreate() method add the following code to create Firebase Authentication Instance. Also Adding onclickListener for register and login buttons.

Button registerBtn = findViewById(R.id.register);
final Button loginBtn = findViewById(R.id.login);
email = findViewById(R.id.email);
password = findViewById(R.id.password);
progressBar = findViewById(R.id.progressBar);
forgetPassword = findViewById(R.id.forget);
firebaseAuth = FirebaseAuth.getInstance();
registerBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this,RegisterActivity.class));
}
});

loginBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String tex_email = email.getText().toString();
String tex_password = password.getText().toString();
if (TextUtils.isEmpty(tex_email) || TextUtils.isEmpty(tex_password)){
Toast.makeText(MainActivity.this, "All Fields Required", Toast.LENGTH_SHORT).show();
}
else{

login(tex_email,tex_password);
}
}
});

Then, Cretae login method that takes two String parameters for Email and password. This method will uses firebaseAuth to create sign In Method with email and password. You can use the following method.

private void login(String tex_email, String tex_password) {
progressBar.setVisibility(View.VISIBLE);
firebaseAuth.signInWithEmailAndPassword(tex_email,tex_password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
progressBar.setVisibility(View.GONE);
if (task.isSuccessful()){
Intent intent = new Intent(MainActivity.this,StartActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();

}else{
Toast.makeText(MainActivity.this, task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
}
});

}

Great Job, Now the users can login to you app using thier email address and password, but first they need to register. So, open register activity and create general object for XML layout file. as following.

private MaterialEditText userName,emailAddress,password,mobile;
private RadioGroup radioGroup;
private Button registerBtn;
private ProgressBar progressBar;
private FirebaseAuth firebaseAuth;

Then in onCreate() method of register activity add the following code.

setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Register");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(RegisterActivity.this,MainActivity.class));
}
});

firebaseAuth = FirebaseAuth.getInstance();

userName = findViewById(R.id.username);
emailAddress = findViewById(R.id.email);
password = findViewById(R.id.password);
mobile = findViewById(R.id.mobile);
radioGroup = findViewById(R.id.radioButton);
registerBtn = findViewById(R.id.register);
progressBar = findViewById(R.id.progressBar);

Next, You need to set the OnClickListener of register Button. Use the following code in onCreate() method.

registerBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final String user_name = userName.getText().toString();
final String email = emailAddress.getText().toString();
final String txt_password = password.getText().toString();
final String txt_mobile = mobile.getText().toString();
int checkedId = radioGroup.getCheckedRadioButtonId();
RadioButton selected_gender = radioGroup.findViewById(checkedId);
if (selected_gender == null){
Toast.makeText(RegisterActivity.this, "Select gender please", Toast.LENGTH_SHORT).show();
}
else {
final String gender = selected_gender.getText().toString();
if(TextUtils.isEmpty(user_name) || TextUtils.isEmpty(email) || TextUtils.isEmpty(txt_password) ||
TextUtils.isEmpty(txt_mobile)){
Toast.makeText(RegisterActivity.this, "All fields are required", Toast.LENGTH_SHORT).show();
}

else{
register(user_name,email,txt_password,txt_mobile,gender);
}
}

}

});

Then in the register activity create register() method the takes five parameter for user name, email, password, mobile and gender. The register method user firebaseAuth to create user with email and password and if task is successful it will send verification email to the user. After that it will directs the user to login activity to make the user login to start activity.

private void register(final String user_name, final String email, String txt_password, final String txt_mobile, final String gender) {
progressBar.setVisibility(View.VISIBLE);
firebaseAuth.createUserWithEmailAndPassword(email,txt_password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
@RequiresApi(api = Build.VERSION_CODES.KITKAT)
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()){
FirebaseUser rUser = firebaseAuth.getCurrentUser();
rUser.sendEmailVerification().addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (task.isSuccessful()){
Intent intent = new Intent(RegisterActivity.this,MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK| Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}else{

Toast.makeText(RegisterActivity.this, Objects.requireNonNull(task.getException()).getMessage(), Toast.LENGTH_SHORT).show();
}
}
});


}else{

progressBar.setVisibility(View.GONE);
Toast.makeText(RegisterActivity.this, Objects.requireNonNull(task.getException()).getMessage(), Toast.LENGTH_SHORT).show();

}
}
});


}

Finally, run your app and try to register with a true email and if their is error please type your comment.

Thank You

Firebase Facebook Authentication Android Studio

Related posts

Leave a Comment