Android Login and Registration with Firebase Cloud Firestore

Step by step guide

Rey
5 min readFeb 8, 2020

--

In this article I will walk you through an easy method to develop a login and registration application on Android Studio with Cloud Firestore. Now, let me tell you why I chose Cloud Firestore over RealTime Database. Recenlty, during the process of working on a project I noticed that the internet already had a lot of help to offer with RealTime Firebase while several others including myself had trouble getting help with CloudFirestore which is apparently the newest release after the RealTime Database. By way of trial and error, along with help of the documentation for Cloud Firestore I figured my way through. If you need to authenticate a user based on other attributes apart from email and password and don’t wish to mess around with Firebase Auth custom authentication here’s the answer. So let me save you some valuable hours of coding and lets get started.

Connecting your app to Firebase

Head on to firebase.google.com > Go to console > Add project(e.g. Test01 )> Provide a project name > Click Create Project.

You’ll be directed to the screen below. Click on the Android icon marked in red

Check out the link below for the last few steps which are pretty straightforward. You need to follow up from Step 2 if you’ve chosen Option 1.

In the end you should have the following dependencies included in the file build.gradle (Module:app)

implementation 'com.google.firebase:firebase-core:17.0.0'
implementation 'com.google.firebase:firebase-firestore:20.1.0'
}
apply plugin: 'com.google.gms.google-services'

The following dependency needs to be added in the Project level gradle file. Note that you might need to change the version number based on the latest release.

classpath 'com.google.gms:google-services:4.2.0'

You should also have the google-services.json file included in the app folder of your project. Do a project sync, with that you should have successfully connected Firebase to your Android Studio project.

Alright folks now let’s get to coding.

User Registration

Let me brief up on what you should expect here. Once the user provides the necessary inputs and clicks on the register button a ‘Toast’ message should show up stating that you have successfully registered and you should be able to login using those credentials. In the event that you enter existing credentials you’d be prompted to re-enter again. So now we’re good to start off with the java code.

FirebaseFirestore firebaseFirestore;
DocumentReference ref;
firebaseFirestore=FirebaseFirestore.getInstance();

We begin by initiating an instance of Firebase Firestore and the DocumentReference as shown in the snippet above. As for Cloud firestore, data or a record is stored in a document which can be referred to using an auto-generated unique identifier by firebase. Several of these documents are stored in a collection. In this case the collection name is ‘client’ and we’re attempting to refer the documents in this collection.

ref = firebaseFirestore.collection("client").document();

The code below lists what needs to be done when the ‘Register’ button is clicked. The nested if condition has a function called documentSnapshot.exist() which checks if the user credentails exists. If not, the data can be successfully added to the collection using the .add(Object data) method.

reg_registration.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(reg_name.getText().toString().equals("")) {
Toast.makeText(Register.this, "Please type a username", Toast.LENGTH_SHORT).show();

}else if(reg_email.getText().toString().equals("")) {
Toast.makeText(Register.this, "Please type an email id", Toast.LENGTH_SHORT).show();

}else if(reg_password.getText().toString().equals("")){
Toast.makeText(Register.this, "Please type a password", Toast.LENGTH_SHORT).show();

}else if(!reg_conf_pwd.getText().toString().equals(reg_password.getText().toString())){
Toast.makeText(Register.this, "Password mismatch", Toast.LENGTH_SHORT).show();

}else {

ref.get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
@Override
public void onSuccess(DocumentSnapshot documentSnapshot) {

if (documentSnapshot.exists())
{
Toast.makeText(Register.this, "Sorry,this user exists", Toast.LENGTH_SHORT).show();
} else {
Map<String, Object> reg_entry = new HashMap<>();
reg_entry.put("Name", reg_name.getText().toString());
reg_entry.put("Email", reg_email.getText().toString());
reg_entry.put("Password", reg_password.getText().toString());

// String myId = ref.getId();
firebaseFirestore.collection("client")
.add(reg_entry)
.addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
@Override
public void onSuccess(DocumentReference documentReference) {
Toast.makeText(Register.this, "Successfully added", Toast.LENGTH_SHORT).show();
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Log.d("Error", e.getMessage());
}
});
}
}
});
}
}
});

Designing the interface is pretty straightforward, check out the github link below for the code in activty_register.xml.

Registration Layout

User Login

Similar to the registration code we once again need to initiate an instance of Firebase Firestore and instead of documentReference we have introduced QueryDocumentSnapshot which contains the fetched data. It runs inside a for loop where the current inputs are checked against each of the documents containing user data.

In the event of clicking the ‘Login’ button the following lines are executed.

public void onClick(View v){
switch(v.getId()){
case R.id.btn_login:
if(email.getText().toString().equals("")){
Toast.makeText(MainActivity.this, "Please enter valid email", Toast.LENGTH_SHORT).show();
}else if( pwd.getText().toString().equals("")){
Toast.makeText(MainActivity.this, "Please enter valid password", Toast.LENGTH_SHORT).show();
}
db.collection("client")
.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
if(task.isSuccessful()){
for(QueryDocumentSnapshot doc : task.getResult()){
String a=doc.getString("Email"); String b=doc.getString("Password");
String a1=email.getText().toString().trim();
String b1=pwd.getText().toString().trim();
if(a.equalsIgnoreCase(a1) & b.equalsIgnoreCase(b1)) {
Intent home = new Intent(MainActivity.this, home_activity.class);
startActivity(home);
Toast.makeText(MainActivity.this, "Logged In", Toast.LENGTH_SHORT).show();
break;
}else
Toast.makeText(MainActivity.this, "Cannot login,incorrect Email and Password", Toast.LENGTH_SHORT).show();

}

}
}
});


break;

case R.id.btn_register:
Intent register_view=new Intent(MainActivity.this,Register.class);
startActivity(register_view);
break;
}

Also, don’t forget the trim() function for text field inputs, it prevents unexpected results due to unseen trailing spaces.

Check out my github for the code in activity_main.xml for the interface design.

Login Layout

That’s it folks. You can find the full code HERE. By now you should have a successful login and registration feature in your application.

Happy coding!

--

--