Adding Firebase functionality in your app | Part 2 Creating Firebase Authentication

Introduction:
In this post, we will create a Login and Registration Page with Firebase authentication, we will accept the name, email, password of the user and register the user with the Firebase auth library.

Implementation:

  1. First, we need to enable authentication for our project, go to the Firebase console, select Authentication from the left panel and then sign-in method, enable email method.
  2. In AS, go-to the assistant, in the right panel, select Authentication, click connect to Firebase, it will be in green when connected, second select Add Authentication to the project, Accept changes and finish.
  3. Now you can start coding.
  4. Create an Empty Activity, named as SignUp
  5. Go to SignUp.xml and add the following XML.

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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:padding="20dp"
tools:context="SignUp">
<TextView
android:id="@+id/register"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="51dp"
android:text="Sign Up"
android:textColor="@color/colorPrimary"
android:textSize="25sp"
android:textStyle="bold"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<EditText
android:id="@+id/name"
android:layout_width="match_parent"
android:layout_height="50dp"
android:padding="10dp"
android:layout_marginTop="30dp"
android:ems="10"
android:inputType="textPersonName"
android:hint="Name"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/register" />
<EditText
android:id="@+id/email"
android:layout_width="match_parent"
android:layout_height="50dp"
android:padding="10dp"
android:layout_marginTop="42dp"
android:layout_marginEnd="4dp"
android:layout_marginRight="4dp"
android:ems="10"
android:inputType="textEmailAddress"
android:hint="Email Address"
app:layout_constraintEnd_toEndOf="@+id/name"
app:layout_constraintTop_toBottomOf="@+id/name" />
<EditText
android:id="@+id/password"
android:layout_width="match_parent"
android:layout_height="50dp"
android:padding="10dp"
android:layout_marginStart="2dp"
android:layout_marginLeft="2dp"
android:layout_marginTop="48dp"
android:ems="10"
android:inputType="text"
android:hint="Password"
app:layout_constraintStart_toStartOf="@+id/email"
app:layout_constraintTop_toBottomOf="@+id/email" />
<Button
android:id="@+id/signupButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="32dp"
android:text="Register"
android:textColor="@android:color/white"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/password" />
<TextView
android:id="@+id/singinLink"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:text="Already have an account?"
android:textSize="15sp"
android:textAllCaps="true"
android:textColor="@color/colorAccent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/signupButton" />
</androidx.constraintlayout.widget.ConstraintLayout>
The XML file defines three EditText for user input and Button.

Add the following java code to read the input and create an account with the Firebase

// I haven't add imported files, but those will be added by clicking Alt + Enter
public class SignUp extends AppCompatActivity {
private EditText name, email, password; //out input fields
private FirebaseAuth firebaseAuth; // firebase auth object
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_up);
name = findViewById(R.id.name);
email = findViewById(R.id.email);
password = findViewById(R.id.password);
firebaseAuth = FirebaseAuth.getInstance();
findViewById(R.id.singinLink).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(SignUp.this, SignIn.class)); // if account exists go to login page
}
});
findViewById(R.id.signupButton).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
createAccount();
}
});
}
// function to create account on button click
private void createAccount() {
// read inputs
final String nameText = name.getText().toString().trim();
final String emailText = email.getText().toString().trim();
String passwordText = password.getText().toString().trim();
firebaseAuth.createUserWithEmailAndPassword(emailText, passwordText)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
Toast.makeText(getApplicationContext(), "Account Created!", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "Problem occurred!" + task.getException().getLocalizedMessage(), Toast.LENGTH_SHORT).show();
}
}
});
}
}
view raw SignUp.java hosted with ❤ by GitHub

If everything is done correctly, you would be able to create an account with your email, when created check the Firebase console user section and you'll see a new account added.
Now let's implement Login Page

Create a new activity, named SignIn
Go to layout_signin.xml and add the following code:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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:padding="20dp"
tools:context="SignIn">
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="51dp"
android:layout_marginBottom="411dp"
android:text="Sign In"
android:textColor="@color/colorPrimary"
android:textSize="25sp"
android:textStyle="bold"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<EditText
android:id="@+id/emailAddress"
android:layout_width="match_parent"
android:layout_height="50dp"
android:padding="10dp"
android:layout_marginTop="59dp"
android:ems="10"
android:hint="Email Address"
android:inputType="textEmailAddress"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/textView" />
<EditText
android:id="@+id/passwordSignin"
android:layout_width="match_parent"
android:layout_height="50dp"
android:padding="10dp"
android:layout_marginTop="50dp"
android:ems="10"
android:hint="Password"
android:inputType="textPassword"
app:layout_constraintStart_toStartOf="@+id/emailAddress"
app:layout_constraintTop_toBottomOf="@+id/emailAddress" />
<Button
android:id="@+id/siginButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="50dp"
android:text="Login"
android:textColor="@android:color/white"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/passwordSignin" />
<TextView
android:id="@+id/registerLink"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="29dp"
android:text="Create new account"
android:textSize="15sp"
android:textAllCaps="true"
android:textColor="@color/colorAccent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/siginButton" />
</androidx.constraintlayout.widget.ConstraintLayout>
Here we have created two input fields to accept email and password
Add the following java code in SignIn.java

//import everything
public class SignIn extends AppCompatActivity {
private EditText email;
private EditText password;
private Button signIn;
private TextView register;
private FirebaseAuth firebaseAuth;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_in);
email = findViewById(R.id.emailAddress);
password = findViewById(R.id.passwordSignin);
signIn = findViewById(R.id.siginButton);
register = findViewById(R.id.registerLink);
loading = findViewById(R.id.loading);
firebaseAuth = FirebaseAuth.getInstance();
register.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(SignIn.this, SignUp.class));
}
});
signIn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
sigInUser();
}
});
}
private void sigInUser() {
String emailText = email.getText().toString().trim();
String passwordText = password.getText().toString().trim();
firebaseAuth.signInWithEmailAndPassword(emailText, passwordText)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
Toast.makeText(SignIn.this, "Authentication success.",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(SignIn.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
}
}
});
}
}
view raw SiginIn.java hosted with ❤ by GitHub
Once, done you can view the Toast to see whether it works or not.
When you launch the app, you have to enter email and password every time to reduce that work, you can do the following in the first activity in your app, in my case, it is SignIn.java

// pu this inside the class
@Override
protected void onStart() {
super.onStart();
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if(user != null) {
//if user is authenticated give him access to the app
}
}
view raw inside hosted with ❤ by GitHub

If you have any doubts, please comment in the section below.

Popular posts from this blog

Audio de-noising using Python (Wavelets)

Converting HTML5 Game for Android | 2 Methods

Display a table in JFrame UI from MySQL Table