How to retrieve data from Firebase Cloud Firestore in Android studio | Quiz App | Java | Android

Golap Gunjan Barman
5 min readFeb 3, 2021

In this blog post, we are going to see how to retrieve data from the Cloud Firestore in the android app. Before going to start, let’s see what Cloud Firestore is.

What is Cloud Firestore?

  • Cloud Firestore is a NoSQL document database that lets you easily store, sync, and query data for your mobile and web apps — at a global scale.
  • In Cloud Firestore, you can structure your data easily with collections and documents. Build hierarchies to store related data and easily retrieve the data you need using expressive queries. All queries scale with the size of your result set (note: not your data set), so your app is ready to scale from day one.
  • Cloud Firestore ships with mobile and web SDKs and a comprehensive set of security rules so you can access your database without needing to stand up your server. Using Cloud Functions, the serverless compute product, you can execute hosted backend code that responds to data changes in the database. Of course, you can access Cloud Firestore with traditional client libraries too (i.e. Node, Python, Go, and Java).
  • With Cloud Firestore, you can automatically synchronize your app data between devices. We’ll notify you of data changes as they occur so you can easily build collaborative experiences and real-time apps.
  • Powered by Google’s storage infrastructure, Cloud Firestore is built to scale with your business. Now, you can focus on building your app instead of managing servers or worrying about consistency.

What you’re looking for

Here I create a Quiz app using cloud firestore. Demo video:

Create a Cloud Firestore database

  • If you haven’t already, create a Firebase project: In the Firebase console, click Add project, then follow the on-screen instructions to create a Firebase project or to add Firebase services to an existing GCP project.
  • Navigate to the Cloud Firestore section of the Firebase console. You’ll be prompted to select an existing Firebase project. Follow the database creation workflow.
  • Select a starting mode for your Cloud Firestore Security Rules:

Test mode

  • Good for getting started with the mobile and web client libraries, but allows anyone to read and overwrite your data. After testing, make sure to review the Secure your data section.
  • To get started with the web, iOS, or Android SDK, select test mode.

Locked mode

  • Denies all reads and writes from mobile and web clients. Your authenticated application servers (C#, Go, Java, Node.js, PHP, Python, or Ruby) can still access your database.
  • To get started with the C#, Go, Java, Node.js, PHP, Python, or Ruby server client library, select locked mode.

Here I select Test Mode, but I changed my rule a little bit. When a user logged into my app only that user will access my database. So you can change your rules according to your requirements.

  • Select a location for your database.
  • This location setting is your project’s default Google Cloud Platform(GCP) resource location. Note that this location will be used for GCP services in your project that require a location setting, specifically, your default Cloud Storage bucket and your App Engine app (which is required if you use Cloud Scheduler).
  • If you aren’t able to select a location, then your project already has a default GCP resource location. It was set either during project creation or when setting up another service that requires a location setting.

Warning: After you set your project’s default GCP resource location, you cannot change it.

  • Click Done.

Set up environment

Add the required dependencies and client libraries to your app.

dependencies {
implementation ‘com.google.firebase:firebase-analytics:17.3.0’
implementation ‘com.google.firebase:firebase-firestore:21.4.2’
}

Add data

  • Cloud Firestore stores data in Documents, which are stored in Collections. Cloud Firestore creates collections and documents implicitly the first time you add data to the document. You do not need to explicitly create collections or documents.
  • Here we add our data manually, which means we are not coding for adding data into our app, we will add it manually. For that go to the Cloud Firestore and add it.
  • As I create a Quiz app, so I add data according to my requirements. The below images will give you a clear view of my cloud database.
My Firestore database
Hierarchy

Initialize Cloud Firestore

Initialize an instance of Cloud Firestore:

public class SplashActivity extends AppCompatActivity {
private FirebaseFirestore firestore;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.
activity_splash);
firestore = FirebaseFirestore.
getInstance();
}

}

Read Data

Now use “get” method to retrieve the entire collection.

  • Retrieve the Categories:

firestore.collection(“QUIZ”).document(“Categories”)
.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
@Override
public void onComplete(@NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()){
DocumentSnapshot doc = task.getResult();

if (doc.exists()){
long count = (long)doc.get(“COUNT”);
for (int i=1; i<=count; i++){
String catName = doc.getString(“CAT” + String.
valueOf(i));
catList.add(catName);
}
Intent intent = new Intent(SplashActivity.this, SignIn.class);
startActivity(intent);
SplashActivity.this.finish();
}else {
Toast.
makeText(SplashActivity.this, “No Category document exists”, Toast.LENGTH_SHORT).show();
finish();
}
}else
{
Toast.
makeText(SplashActivity.this, task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
}
});

  • Retrieve the Sets:

firestore.collection(“QUIZ”).document(“CAT” + String.valueOf(category_id))
.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
@Override
public void onComplete(@NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()){
DocumentSnapshot doc = task.getResult();
if (doc.exists()){
long sets = (long)doc.get(“SETS”);
SetsGridAdapter adapter = new SetsGridAdapter((int)sets);
setGridView.setAdapter(adapter);
}else {
Toast.
makeText(SetsActivity.this, “No CAT document exists”, Toast.LENGTH_SHORT).show();
finish();
}
}else
{
Toast.
makeText(SetsActivity.this, task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
loadingDialog.cancel();
}
});

  • Retrieve the Questions:

firestore.collection(“QUIZ”).document(“CAT” + String.valueOf(category_id))
.collection(“SET” + String.
valueOf(setNo))
.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()){
QuerySnapshot questions = task.getResult();

for (QueryDocumentSnapshot doc : questions){
questionList.add(new Question(doc.getString(“QUESTION”),
doc.getString(“A”),
doc.getString(“B”),
doc.getString(“C”),
doc.getString(“D”),
Integer.
valueOf(doc.getString(“ANSWER”))
));
}
setQuestion();
}else
{
Toast.
makeText(QuestionsActivity.this, task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
loadingDialog.cancel();
}
});

For full code visit my GitHub account

https://github.com/barmangolap15/
https://github.com/barmangolap15/

--

--

Golap Gunjan Barman

Hi everyone, myself Golap an Android app developer with UI/UX designer.