How to build A Science Quiz Android App - Hive Programmers

avatar

Greetings to everyone on StemSocial and on Hive.

It's @skyehi and I'm super excited to be back to continue my series on Android App development Tutorial For beginners.

This going to be a special tutorial guys because it's more like a basic science game App. A Quiz is one of the best ways to learn new things, discover how much you know about a subject or topic and have fun while doing all that.

Polish_20231215_121800338.jpgOriginal Image Source by Pixabay from Pexels

YpihifdXP4WNbGMdjw7e3DuhJWBvCw4SfuLZsrnJYHEpsqZFkiGGNCQTayu6EytKdg7zA3LL2PbZxrJGpWk6ZoZvBcJrADNFmaFEHagho8WsASbAA8jrpnELSvRtvjVuMiU1C5ADFX1vJgcpDvNtue9Pq83tjBKX62dqT5UoxtDk.png

In today's blog we're going to be building a quiz App. Since it's a beginner's guide, I'll take you through building the complete App but I'll leave the questions setup to you guys.

You can put in any question you want to and also add the possible answers for your users to choose from. This is going to be a really fun project guys.

At the end of this tutorial, you would have built your very first Android Quizz App which you can run on your physical Android device and show to your friends.

Since StemSocial is a science community, I'll be setting science questions in my own app but you can set any question you want to guys.

Let's get started with our App project shall we.

2dk2RRM2dZ8gKjXsrozapsD83FxL3Xbyyi5LFttAhrXxr16mCe4arfLHNDdHCBmaJroMz2VbLrf6Rxy9uPQm7Ts7EnXL4nPiXSE5vJWSfR53VcqDUrQD87CZSpt2RKZcmrYrze8KanjkfyS8XmMCcz4p33NZmfHE4S9oRo3wU2.png

Setting Up Your Android Project

Alright guys I'll assume you already have Android Studio IDE and JDK successfully installed on your PC in order to successfully go through with this tutorial.

If you're having troubles installing the softwares, please let me know in the comments.

Let's start by creating a new Android Project. So guys go ahead and open Android Studio on your PC and click on "Create a new Android Project".

As usual guys let's choose an Empty Activity template as the template of our Android App project.

Choose the App name and set a package name for your App. I'll probably just call mine Stem Quiz.

Also guys, do not forget to set Java as the programming language. You can choose Kotlin if you're familiar with that programming language but I'll still be using Java for our basic tutorial series.

When you're satisfied with the project setup, click finish, sit back and let Android Studio prepare your App project for you.

YpihifdXP4WNbGMdjw7e3DuhJWBvCw4SfuLZsrnJYHEpsqZFkiGGNCQTayu6EytKdg7zA3LL2PbZxrJGpWk6ZoZvBcJrADNFmaFEHagho8WsASbAA8jrpnELSvRtvjVuMiU1C5ADFX1vJgcpDvNtue9Pq83tjBKX62dqT5UoxtDk.png

Designing Our Quiz Layout

It's time to work on my favourite part of developing Apps, the frontend. In our simple Quizz App we'll have three main elements.

Through this tutorial I'll be introducing you to RadioGroup elements. This is the best element to use if you want to build an App that would require users to choose from a list of options. You would usually have empty circles next to a list of items to choose from.

The item the user would choose would have its circle light up with a different color. This will be a great element to use for our possible answers in the Quizz App.

We'll also have a textview which will hold the Questions we want to ask and finally we'll have a submit button. After the user is done selecting the answer, he or she can press the submit button and our App will show whether it's correct or wrong with a toast message.

The front end layout design code will be written inside the res/layout/activity_main.xml file.

Here's how your code should look like guys

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="16dp"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/questionTextView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Question text here"/>

    <RadioGroup
        android:id="@+id/answerGroup"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        (html comment removed:  Radio buttons for answer choices )

    </RadioGroup>

    <Button
        android:id="@+id/submitBtn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Submit"/>

</LinearLayout>

YpihifdXP4WNbGMdjw7e3DuhJWBvCw4SfuLZsrnJYHEpsqZFkiGGNCQTayu6EytKdg7zA3LL2PbZxrJGpWk6ZoZvBcJrADNFmaFEHagho8WsASbAA8jrpnELSvRtvjVuMiU1C5ADFX1vJgcpDvNtue9Pq83tjBKX62dqT5UoxtDk.png

Creating Question and Answer Classes

Now guess our Quizz App will hold Question and Answer Data. This means we would need to create two classes. One class will represent the Question Data and we'll call that Java class Question.java. The other class will represent our App's answers data and we'll call that Java class Answer.java.

This is going to be a simple and straight forward code guys.

Here's how your code should look like

For The Question and Answer Java Class

// Question.java
public class Question {
    private String questionText;
    private List<Answer> answerList;
    private int correctAnswerIndex;

    // Constructor, getters, and setters
}

// Answer.java
public class Answer {
    private String answerText;

    // Constructor, getters, and setters
}

YpihifdXP4WNbGMdjw7e3DuhJWBvCw4SfuLZsrnJYHEpsqZFkiGGNCQTayu6EytKdg7zA3LL2PbZxrJGpWk6ZoZvBcJrADNFmaFEHagho8WsASbAA8jrpnELSvRtvjVuMiU1C5ADFX1vJgcpDvNtue9Pq83tjBKX62dqT5UoxtDk.png

Implementing our Quiz Logic

It's now time to write the logic of our Quizz App guys. This is the part where we initialize all the elements we created in res/layout/activity_main.xml file which includes the textview, the Radio group and the textview.

After writing the basic logic of our Quizz functionality we'll go ahead and populate it with custom questions and possible answers. That's where you decide what questions your user will be asked.

The main logic code of our App will of course be written inside your MainActivity.java file.

Here's how your logic code should look like guys

// MainActivity.java
public class MainActivity extends AppCompatActivity {

    private TextView questionTextView;
    private RadioGroup answerGroup;
    private Button submitBtn;

    private List<Question> questionList;
    private int currentQuestionIndex;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Initialize views
        questionTextView = findViewById(R.id.questionTextView);
        answerGroup = findViewById(R.id.answerGroup);
        submitBtn = findViewById(R.id.submitBtn);

        // Initialize and populate questionList
        questionList = new ArrayList<>();
        populateQuestionList(); // Implement this method

        // Set up initial question
        showQuestion();

        // Set up onClickListener for the submit button
        submitBtn.setOnClickListener(v -> checkAnswer());
    }

    private void showQuestion() {
        // Display current question and its answer choices
        Question currentQuestion = questionList.get(currentQuestionIndex);
        questionTextView.setText(currentQuestion.getQuestionText());

        // Populate radio buttons with answer choices
        answerGroup.removeAllViews();
        for (int i = 0; i < currentQuestion.getAnswerList().size(); i++) {
            RadioButton radioButton = new RadioButton(this);
            radioButton.setText(currentQuestion.getAnswerList().get(i).getAnswerText());
            answerGroup.addView(radioButton);
        }
    }

    private void checkAnswer() {
        // Check if the selected answer is correct
        int selectedAnswerIndex = answerGroup.indexOfChild(findViewById(answerGroup.getCheckedRadioButtonId()));
        boolean isCorrect = selectedAnswerIndex == questionList.get(currentQuestionIndex).getCorrectAnswerIndex();

        // Provide feedback (Toast or Dialog)
        if (isCorrect) {
            showToast("Correct!");
        } else {
            showToast("Wrong! The correct answer is " +
                    questionList.get(currentQuestionIndex).getAnswerList().get(questionList.get(currentQuestionIndex).getCorrectAnswerIndex()).getAnswerText());
        }

        // Move to the next question or finish the quiz
        if (currentQuestionIndex < questionList.size() - 1) {
            currentQuestionIndex++;
            showQuestion();
        } else {
            showToast("Quiz completed!");
            // Handle quiz completion, e.g., show score or restart quiz
        }
    }

    private void showToast(String message) {
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
    }
}

With the logic of our App, if the user selects the right answer, a toast message will appear saying "Correct!" But if the user chooses the wrong answer, a toast message will appear saying "Wrong! The correct answer is" and would include the right answer.

I think this would be a fun app right guys. Use very interesting questions and I can assure you that your users will enjoy themselves with your app.

YpihifdXP4WNbGMdjw7e3DuhJWBvCw4SfuLZsrnJYHEpsqZFkiGGNCQTayu6EytKdg7zA3LL2PbZxrJGpWk6ZoZvBcJrADNFmaFEHagho8WsASbAA8jrpnELSvRtvjVuMiU1C5ADFX1vJgcpDvNtue9Pq83tjBKX62dqT5UoxtDk.png

Populating Question List

It's now time for the final part of our App, this is the code in which your questions and answers will exist. You can add as many questions with their possible answers as you wish to guys.

This step will also be written inside your
MainActivity.java file after the final toast messages above.

So we're just creating a method called populateQuestionList() to fill your questionList with actual questions and answers.

Here's how your code should look like

private void populateQuestionList() {
    // Add questions and answers to questionList
    // Example:
    Question question1 = new Question("What is the capital of France?");
    question1.setAnswerList(Arrays.asList(new Answer("Berlin"), new Answer("Paris"), new Answer("Rome")));
    question1.setCorrectAnswerIndex(1);

    Question question2 = new Question("Which planet is known as the Red Planet?");
    question2.setAnswerList(Arrays.asList(new Answer("Mars"), new Answer("Venus"), new Answer("Jupiter")));
    question2.setCorrectAnswerIndex(0);

    // Add more questions...

    questionList.add(question1);
    questionList.add(question2);
    // Add more questions...
}

2dk2RRM2dZ8gKjXsrozapsD83FxL3Xbyyi5LFttAhrXxr16mCe4arfLHNDdHCBmaJroMz2VbLrf6Rxy9uPQm7Ts7EnXL4nPiXSE5vJWSfR53VcqDUrQD87CZSpt2RKZcmrYrze8KanjkfyS8XmMCcz4p33NZmfHE4S9oRo3wU2.png

Congratulations guys, you've now created a simple Science Quiz Android App. You are Free to Customize the questions and answers, enhance the UI, and add more features based on your preferences.

To make you easily understand how to add questions, I added a simple question about what is the capital of France and with a nice science question about which planet is known as the Red planet? I hope the science geeks know the answer to this question. Alright it's Mars.

You can now run your App on either your physical Android device or an emulator.

When the App launches you can go ahead and answer the questions you set and check out the answers. Everything should work perfectly fine with the codes I have provided. Have fun building your very own Quizz App guys.

Thank you so much for taking the time to read today's blog. I hope you enjoyed our simple Quizz App guys.

If you're having trouble writing the code, running the app or installing the necessary setups, please let me know in the comments.

Have a lovely day and catch you next time in StemSocial. Goodbye 👨‍💻


You Can Follow Me @skyehi For More Like This And Others



0
0
0.000
1 comments
avatar

Thanks for your contribution to the STEMsocial community. Feel free to join us on discord to get to know the rest of us!

Please consider delegating to the @stemsocial account (85% of the curation rewards are returned).

Thanks for including @stemsocial as a beneficiary, which gives you stronger support. 
 

0
0
0.000