Android Quiz App with Firebase

ACES PVGCOET
1 Hour Blog Series
Published in
7 min readMar 2, 2021

Create a simple Android quiz application in this tutorial! Learn Android studio, Firebase, UI and many more!

Introduction

Android is a mobile operating system, designed primarily for touchscreen mobile devices such as smartphones and tablets and Android Studio is the official integrated development environment for Google’s Android operating system, built on JetBrains’ IntelliJ IDEA software and designed specifically for Android development.

Tools, Software and some prerequisites

  • Android Studio and Software Development Kit — the official integrated development environment (IDE) developed by Google.
    (If you are completely new to this environment and need help to Download/Install it, just follow the below links of their official walkthrough:
    Download Android Studio — https://developer.android.com/studio .
    Install Android Studio — https://developer.android.com/studio/install )
  • Have basic understanding on how to use Android Studio
  • Some foundational knowledge of java and there you go!

Overview

So Basically, the app would have four views-

  1. First would be the main page with logo and a begin button.
  2. Second one for a list of topics.
  3. Third would be a list of questions.
  4. And finally, the view where the question and its respective options would be displayed for the user to choose from.

Let’s Begin!

1] View 1
So, beginning with the UI for the first Page, just add a simple logo or an image and a button to take you from your landing page to the next view of topics in the app. You can use drag and drop options in the “Design” view of your android studio to make things a little simpler!
Here’s an example of how it would look. You all are free to go ahead with your own creativity and customise your app’s looks by combining different colours and fonts as per your innovation!

Note –

  1. If you are using any image for the UI, make sure to save/download it in the “drawable” folder which you will find in app\src\main\res\drawable of your project.
  2. Also, for all the views from now on, do not forget to constrain all the elements that you use to the nearest other elements or the margins of the page and give appropriate IDs to them.
  3. And Lastly, if stuck at any stage, feel free to paste your error onto google as most of the people have faced and discussed the same problems and solutions there!

2] View 2,3

Next, add another activity as “TopicsPage” and add a List view there to list all the topics that the app would have, at one glance.

Android ListView is basically a view which groups several items and display them in vertical scrollable list. If you wish to know in detail about list view, you can always find more information in official documentation of Android — https://developer.android.com/reference/android/widget/ListView

The list view would be blank for now, and we will add contents to it soon.
Similarly, create another activity with same widgets for listing out MCQs of that topic.
Link the clicking of the begin button to open this TopicsPage Activity that we just created.

begin = (Button)findViewById(R.id.btnBegin);
begin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, TopicsPage.class);
startActivity(intent);
}
});

3] Firebase

Firebase is a platform developed by Google for creating mobile and web applications.
In order to save the required data, we would be using cloud firestore.

Steps –

  1. Open firebase site- https://firebase.google.com/ .
  2. Create a new project for your application
  3. Add a new database in “cloud firestore” section
  4. Click on settings, and connect this project to your android application by following the details steps provided here — https://firebase.google.com/docs/android/setup .
  5. Once you connect your app with your firebase, click on “sync now” to refresh your gradle build

New Project

Add new database to cloud firestore

Connect with your android app

Once a successful connection is established, click on “new collection” and add a new collection. For example-topics.

Inside this collection, add individual topic documents with name, for example — History, World, etc.

Inside each document, add another collection for MCQs, example — quizquestions

Then again add all the MCQs for that respective topic in the form of documents inside the quizquestions collection that we already created.

Finally, inside each MCQ document, add five fields for Question, option A, option B, option C, option D and Correct Answer respectively.

4] View 2,3

Next, we head over to the java files of Topics and MCQs activities

  1. Add one more class in it for topic name
class topicName {
String id,name;
topicName(String id,String name){
id = "";
name = "NULL";
}
void setId(String id,String Name){
this.id = id;
this.name = Name;
}
}

2.  Create a firestore instance, and two arraylists of topicNames and ids

FirebaseFirestore db = FirebaseFirestore.getInstance();
ArrayList<topicName> myTopicNames = new ArrayList<topicName>();
ArrayList<String> idArrayList = new ArrayList();

3.  Use the firestore instance to access topics collection and add it to the topic listView through adaptor as follows

final ProgressBar progressBar = (ProgressBar) findViewById(R.id.topicsProgressbar);
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
progressBar.setVisibility(View.GONE);
//progressBarInsideText.setVisibility(View.GONE);
}
}, 3000);db.collection("topics").get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
int count = 1;
for (QueryDocumentSnapshot document : task.getResult())
{
Log.d("tag", document.getId());
String id = "" + document.getId() + "";
String name = "" + document.getData().get("name");
topicName temp = new topicName(id, name);
temp.setId(id + "", name);
myTopicNames.add(temp);
}
int n = myTopicNames.size();
for (int i = 0; i < n; i++) {
idArrayList.add(myTopicNames.get(i).name + "");
}
} else {
Log.d("TAG", "Error getting documents: ", task.getException());
}
}
});
final ArrayAdapter<String> questionsArrayAdapter = new ArrayAdapter<String>
(this, android.R.layout.simple_list_item_1, idArrayList);
final ListView topicsListView = (ListView) findViewById(R.id.topicsListView);
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
topicsListView.setAdapter(questionsArrayAdapter);
topicsListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(Topics.this, QuestionsActivity.class);
intent.putExtra("id", myTopicNames.get(position).id);
intent.putExtra("lang", myTopicNames.get(position).name);
startActivity(intent);
}
});
}
},3000);
}

4.  Note the usage of Handler for Progress Bar till the app fetches information from firebase

5. Follow the exact process for Listing MCQ questions too and also connect all these views through intents.

5] View 4

Finally,

The Main Question Page is to be done.

For The design Part, Simply add a card view on the top for the question and Four Buttons that would represent four respective options.

<androidx.cardview.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="16dp"
android:elevation="5dp"
android:translationZ="3dp"
app:cardBackgroundColor="#BBD3F9"
app:cardCornerRadius="8dp"
app:cardUseCompatPadding="true"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.047">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="150dp"
android:gravity="center"
android:orientation="horizontal">
<TextView
android:id="@+id/qque"
android:layout_width="match_parent"
android:layout_height="130dp"
android:background="#F4DEE5"
android:text="TextView"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.378"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.113" />
</LinearLayout>
</androidx.cardview.widget.CardView>
<Button
android:id="@+id/D"
android:layout_width="200dp"
android:layout_height="60dp"
android:background="#FE6161"
android:text="Button"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.852"
app:layout_constraintCircleRadius="50dp"
/>
<Button
android:id="@+id/C"
android:layout_width="200dp"
android:layout_height="60dp"
android:background="#FE6161"
android:text="Button"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.71" />
<Button
android:id="@+id/B"
android:layout_width="200dp"
android:layout_height="60dp"
android:background="#FE6161"
android:text="Button"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.569" />
<Button
android:id="@+id/A"
android:layout_width="200dp"
android:layout_height="60dp"
android:background="#FE6161"
android:text="Button"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.425" />

Lastly, in the Java file for the same,

  • Fetch data from firestore and save it in local variables
public void getdatafromfirestore(){
final DocumentReference docRef = db.collection("topics").document(id1).collection("quizQuestions").document(id2);
docRef.addSnapshotListener(new EventListener<DocumentSnapshot>() {
@Override
public void onEvent(@Nullable DocumentSnapshot value, @Nullable FirebaseFirestoreException error) {
if(error!=null){
Log.w("TAG",error);
return;
}
if(value!=null && value.exists()){
Log.d("TAG","Current Data " + value.getData());
questName = (String) value.getData().get("0Question");
opa = (String)value.getData().get("A");
opb = (String)value.getData().get("B");
opc = (String)value.getData().get("C");
opd = (String)value.getData().get("D");
Ans = (int)value.getLong("zAnswer").intValue();
qque.setText(questName);
a.setText(opa);
b.setText(opb);
c.setText(opc);
d.setText(opd);
}
else{
Log.d("TAG","Curent Data: NULL");
}
}
});
  • Now simply add action listeners to all the option buttons, and on comparing with the right answer, either turn the button red or green.
a.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
setbtnsGray();
if(Ans==1){
a.setBackgroundColor(Color.GREEN);
}
else {
a.setBackgroundColor(Color.RED);
}
setbtnClickablafalse();
}
});
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
setbtnsGray();
if(Ans==2){
b.setBackgroundColor(Color.GREEN);
}
else {
b.setBackgroundColor(Color.RED);
}
setbtnClickablafalse();
}
});
c.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
setbtnsGray();
if(Ans==3){
c.setBackgroundColor(Color.GREEN);
}
else {
c.setBackgroundColor(Color.RED);
}
setbtnClickablafalse();
}
});
d.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
setbtnsGray();
if(Ans==4){
d.setBackgroundColor(Color.GREEN);
}
else {
d.setBackgroundColor(Color.RED);
}
setbtnClickablafalse();
}
});

Additionally, you could also turn the remaining buttons grey and disable them for one choice-a-time only.

That’s it! Congratulations! You have completed your Basic Quiz app and you can modify, customize it further as and however you want!

Thank you!

Contributed by Shruti Yadav

LinkedIn profile https://www.linkedin.com/in/shruti-yadav-326300199/

--

--