Let’s accomplish a simple Star Wars quiz!

In this post, you'll apprentice how to actualize a Star Wars quiz for Android application Android Studio. This accessible activity is ideal for beginners with aloof a little accomplishments knowledge.

This is what it will attending like eventually – with one question, three answers and a amplitude to say ‘well done’

The best fun you can accept with one hand

If, like abundant of the internet, you would currently say you’re in a “Star Wars mood” again you may feel like testing your ability to see if you absolutely apperceive your Sith from your Jedi. Maybe you appetite to analysis your friends?

In this post, you’ll see how to body a complete Star Wars quiz with your own questions. Or, if you prefer, you can change the accountable entirely. Accomplish it a quiz about agronomics or age-old history. Aloof don’t apprehend to get as abounding takers…

Building a quiz is a absolute aboriginal action for those starting out, as it alone requires a few basal skills. It’s additionally appealing fun and won’t booty too continued (maybe, oh I don’t know, 7 minutes?). I’ll explain aggregate as we go, but it would be acceptable if you already accept a little accomplishments ability afore starting, or are accommodating to do some added analysis to bigger accept everything. Of course, I accept you already accept Android Studio and the Android SDK installed and set up.

With that out of the way, let’s dive in and accord it a shot.

If you get stuck, aloof use the force!

The aboriginal affair you charge to do is actualize a new action with an abandoned activity. I alleged abundance Quiz.

Then jump into the blueprint editor in adjustment to set up your XML. In added words, add and position the angle (buttons, text, images) the way you appetite them on the page.

Most activities will be fabricated up of a java book and an XML blueprint file, alleged MainActivity.java and activity_main.xml respectively. The XML defines area buttons and argument go and the java tells them how to behave and collaborate with the user.

Open up activity_main.xml and click the “Design” appearance tab bottomward the bottom. Alpha boring and bottomward the elements you appetite to use from the box on the larboard to the appearance on the right. For now, abode 5 TextViews (views that appearance text) wherever you like. Anniversary will accept one of these functions:

This is a constrain layout, which agency you charge to ascertain the position in affiliation to anniversary added and the edges of the display. You do this by avaricious the bend of the view, boring it to an ballast point on all four sides, and again accession it amid those coordinates.

When you baddest a view, you’ll see the advantage to adapt some attributes on the right. Remove the argument for now — we’ll add it afterwards — and set an ID for anniversary one. The IDs are what we use to analyze our angle from aural the code. We’ll use these IDs:

Finally, you’re action to set an onClick for the three answers. This will let you annals a user borer on the TextView from aural the code. Baddest anniversary view, annal to the basal of the attributes window, and again baddest “View All Attributes.” Now acquisition area it says onClick and access the afterward respectively:

Hop into MainActivity.java. This shows us the java cipher authoritative the behavior of our views. There’s some “boilerplate code” already here, which basically tells the affairs to act like an action and to acquisition the appropriate XML book as anon as the action is created.

The aboriginal affair to do is abundance the questions and answers in a map. This is a account of strings (words) which anniversary accept an basis and a amount of our choosing. That agency we can abundance our questions and answers with analytic indexes to retrieve later.

To ascertain a new map, you charge this bit of code, placed alfresco the method:

If annihilation comes up accent in red, you’ll charge to bang on the chat and again hit Alt Access in adjustment to acceptation the accordant class, abacus the all-important functions to your Android program.

So, our map is alleged “questions” and now, central the onCreate adjustment (a block of cipher that runs as anon as the affairs is created), we can abide the map with the questions and answers.

So, if I write:

I accept created a new access area the amount is “What is Kylo Ren’s Real Name” and the “key” is “Question1.”

Create as abounding questions this way as you like, authoritative abiding to characterization them accurately as Question1, Question2, Question3, and so on. Likewise, accomplish a appropriate acknowledgment for anniversary one, labelled Right, and two amiss answers for each, labelled WrongA and WrongB.

Here are some examples:

The acceptable affair about this method, is that we can logically retrieve the abutting catechism and its corresponding questions and answers as we go.

Now you’ll charge to add some code. Don’t anguish if this abutting allotment is tricky. Booty your time account through it. You should acquisition it adequately logical.

First, we charge to actualize some variables and commodity references, which will be accessible throughout the program. So alfresco of the onCreate method, write:

questionNo is an accumulation — a accomplished cardinal — which we will use to accumulate clue of which catechism we are on.

Back central the onCreate, afterwards the band which starts setContentView, you charge to locate the angle in your cipher like so:

setContentView tells Java you’re application the XML area you advised earlier, which agency you can now acquisition the accordant angle by application the IDs you gave them earlier.

Now actualize a new method. A adjustment is any allotment of cipher that is calmly aggregate calm central coiled brackets with a name that you can use to “call” it later. onCreate() is a adjustment for example. A adjustment that says “private void” at the alpha is a adjustment that doesn’t acknowledgment any ethics and that won’t be acclimated alfresco of this program.

Your adjustment will be alleged setQuestion() and in actuality we will be accession all the cipher all-important to appearance the questions and answers.

Here’s how it will look:

As you can see, this is artlessly accepting strings — sequences of argument — from the map and assuming them on the TextViews we created.

If you address setQuestion(); at the basal of the onCreate() method, you will “call” this block of cipher and it will barrage at the alpha of the affairs already the angle accept been identified.

Because we’re accepting the catechism application the accumulation questionNo (“QuestionquestionNo agency “Question1”), we can access this amount after in adjustment to get anniversary abutting question.

We are additionally ambience a “tag” on one of the views, which is a advantageous advertence for us to see which of the answers is correct. For now, the actual acknowledgment is consistently action to be the aboriginal option.

If you run the affairs at this point, you should see your aboriginal question, admitting you won’t be able to collaborate with it.

Next, we charge to let our users comedy the game!

This is nice and easy. Back we set our onClick ethics in the XML blueprint book earlier, we basically told Android we would be creating a adjustment (group of code) which would run back anniversary TextView was clicked.

These methods will say “public void” because they’re interacting with addition script. Actuality is the aboriginal one:

This cipher tells us that back Answer1 is clicked, we will get the tag from that view. If the tag says “Correct,” again we will say able-bodied done on the Outcome TextView. Again we’ll advance to the abutting catechism and reload the questions and answers. An “If” account like this works aloof as it does in Excel; as continued as the argumentation in the brackets is accurate, the cipher in the afterward coiled brackets will execute, contrarily the cipher afterward the “else’”will.

If the tag isn’t the one that says “Correct,” again we say “Sorry, amiss answer!” and the bold won’t advance until the user selects the appropriate one.

Now do the aforementioned affair for onAnswer2Click() and onAnswer3Click(), with the aforementioned code. If we capital to be a little added elegant, again we could use a all-around onClickListener, but I anticipate this adjustment is easiest to accept for beginners!

Here’s a acceptable article on allotment the appropriate affectionate of onClickListener.

I acclimated to comedy a bubbler bold that complex shouting “random generator” and again pointing at addition who would accept to drink. It wasn’t abundant of a game.

We charge a altered affectionate of accidental architect appropriate now — one which randomizes our acknowledgment order.

The best way to do this is amount our answers into a list, which gets about sorted and acclimated to abide the TextViews.

It could attending like this:

So we’re creating a new list, again bushing it with accessible answers from our map, again ambiguity it and abacus it to the views. Finally, we analysis if the appearance has the appropriate acknowledgment and again add the tag “correct” if it does!

You could additionally drag the questions themselves if you capital to, by creating a account of numbers and again ambiguity that to change the questionNo integer.

It’s attractive appealing acceptable now, but there are still aloof a few things to abuse afore we can alarm it a day. The app currently crashes as anon as it alcove the end of the account of questions, which isn’t the nicest “farewell.” We can fix that by artlessly endlessly the app already our QuestionNo gets to a assertive point.

Because every catechism has 4 elements in the map (the catechism and three abeyant answers), the admeasurement of the map will be four times greater than the cardinal of questions. Therefore, we can aloof say:

This will appearance “Well Done!” already the amateur gets to the end of the quiz. Easy!

You can additionally brightness things up a little to accomplish your app attending the part. You can change the blush arrangement for instance by branch to the colors.xml book in your action (app > res > ethics > colors.xml). You can change argument blush of your angle in the attributes window. You can additionally change the accomplishments of your app by abacus the afterward band to your activity_main.xml:

Finally, you could add a logo at the top by application an angel appearance and allotment the angel in attributes. Artlessly add the cartoon you appetite to use to app > res > drawable and accomplish abiding they are all lower-case names with no spaces. The accomplished commodity could attending article like this:

With that, you now accept the basal skeleton for your quiz. You can add added questions of your own, or change the affair absolutely if it pleases you. This could be the foundation of a abstraction aid, as able-bodied as a game, and developing it in either of these means will accommodate the absolute claiming to hone and advance your abilities further.

You’ll go to the arch of the chic if you can you amount out how to let users add their own questions.

Oh and if you get stuck, aloof use the force!

Setting up

Showing the questions

Letting the user play

See Also: hack facebook messenger

Random generator!

Final touches

Closing comments

  • The Question
  • 3 Answers
  • The ‘Outcome’
  • Question
  • Answer1
  • Answer2
  • Answer3
  • Outcome
  • onAnswer1Click
  • onAnswer2Click
  • onAnswer3Click

Adding questions

Map questions = new HashMap();
Questions.put(“Question1”, “What is Kylo Ren’s Real Name?”);
questions.put("Question1", "What is Kylo Ren's Real Name?");
questions.put("Right1", "Ben Solo");
questions.put("WrongA1", "Anakin Skywalker");
questions.put("WrongB1", "Mr Cuddles");

questions.put("Question2", "What blush is Darth Maul's ablaze saber?");
questions.put("Right2", "Red");
questions.put("WrongA2", "Blue");
questions.put("WrongB2", "Green");

questions.put("Question3", "What is the explanation of Star Wars: Episode IV?");
questions.put("Right3", "A New Hope");
questions.put("WrongA3", "Return of the Jedi");
questions.put("WrongB3", "Mr Puddle's Picnic");

int questionNo = 1;
TextView outcome;
TextView question;
TextView answer1;
TextView answer2;
TextView answer3;
question = findViewById(R.id.Question);
answer1 = findViewById(R.id.Answer1);
answer2 = findViewById(R.id.Answer2);
answer3 = findViewById(R.id.Answer3);
outcome = findViewById(R.id.Outcome);
private abandoned setQuestion() {
    question.setText(questions.get("Question"   questionNo).toString());
    answer1.setText(questions.get("Right"   questionNo).toString());
    answer1.setTag("Correct");
    answer2.setText(questions.get("WrongA"   questionNo).toString());
    answer3.setText(questions.get("WrongB"   questionNo).toString());

}
public abandoned onAnswer1Click(View v) {
    if (v.getTag() == "Correct") {
        outcome.setText("Well Done!");
        questionNo  ;
        setQuestion();
    } abroad {
        outcome.setText("Sorry, amiss answer!");
    }

}
private abandoned setQuestion() {

    Account currentAnswers = new ArrayList(3);
    currentAnswers.add(questions.get("Right"   questionNo).toString());
    currentAnswers.add(questions.get("WrongA"   questionNo).toString());
    currentAnswers.add(questions.get("WrongB"   questionNo).toString());
    Collections.shuffle(currentAnswers);

    question.setText(questions.get("Question"   questionNo).toString());
    answer1.setText(currentAnswers.get(0).toString());
    answer2.setText(currentAnswers.get(1).toString());
    answer3.setText(currentAnswers.get(2).toString());

    if (answer1.getText() == questions.get("Right"   questionNo).toString()) {
        answer1.setTag("Correct");
    } abroad {
        answer1.setTag("Incorrect");
    }

    if (answer2.getText() == questions.get("Right"   questionNo).toString()) {
        answer2.setTag("Correct");
    } abroad {
        answer2.setTag("Incorrect");
    }

    if (answer3.getText() == questions.get("Right"   questionNo).toString()) {
        answer3.setTag("Correct");
    } abroad {
        answer3.setTag("Incorrect");
    }

}
    accessible abandoned OnAnswer1Click(View v) {
        if (v.getTag() == "Correct") {
            questionNo  ;
            if ((questionNo * 4) > questions.size()) {
                outcome.setText("You Win!");
            } abroad {
                outcome.setText("Well Done!");
                setQuestion();
            }
        } abroad {
            outcome.setText("Try again!");
        }
    }
android:background="@drawable/stars_bg"

Comments