Trivia Quiz App for Android

* * * * (41 ratings)
Trivia Quiz App for Android | App Code for Sale | Hero

Screenshots

Overview

‘Quiz App’ is a native Android template app for quality trivia. This project is easy to use and configure over property list (XML), so there is no need that you know programming.

You can define as many quiz topics as you like, each quiz have unlimited number of questions, for each question there are 4 possible answers and between them you have to define correct answer.

When user select quiz, gameplay screen appears and user have to pick correct answer in 5 seconds. Time is represented visually as 5 lines that will turn to gray when each second pass and they'll change color from green to red depending how much seconds is left. Game also support configurable score system. Application has categories of different quizzes which feature questions from each quiz.

This module has three packages with their set of classes. Main package has all activities while utility classes have a separate package. Then there is package for Twitter classes.

Quizzes Class

Quizzes class holds different categories of quizzes. Each category has questions specific to each quiz. List of categories are shown through listview control and populated with its adapter.

listOfQuizzes = PListHelper.parseQuizzesPlist(PListHelper.readQuizzesListFromAssets(getApplicationContext()));


        if(listOfQuizzes != null)
            listView.setAdapter(new QuizzesListAdapter(Quizzes.this, listOfQuizzes));

Selection of any category results in start of game implemented by class PlayGame.

public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {     
        if(listOfQuizzes != null){
            Intent aQuizIntent = new Intent(Quizzes.this, PlayGame.class);
            Utils.quiz = listOfQuizzes.get(position);
            startActivity(aQuizIntent);
        }
    }

Each quiz-item view in listview is generated by returning getView against each item.

public View getView(int position, View convertView, ViewGroup parent) {
            Log.i("QuizzesPage", "QuizzesListAdapter: getView");
            View view = null;
            if(convertView == null){
                view = LayoutInflater.from(context).inflate(R.layout.row, null);
                final ViewHolder viewHolder = new ViewHolder();
                viewHolder.name = (TextView)view.findViewById(R.id.rTitle);
                viewHolder.description = (TextView)view.findViewById(R.id.rDescription);
                viewHolder.imageName = (ImageView)view.findViewById(R.id.rImage);

                view.setTag(viewHolder);
            }else{
                view = convertView;             
            }
            ViewHolder holder = (ViewHolder)view.getTag();

            holder.name.setText(_listOfQuizzes.get(position).getName());
            holder.description.setText(_listOfQuizzes.get(position).getDescription());

            //menu item image
            String imageName = _listOfQuizzes.get(position).getImageName();
            if(imageName != null){
                AssetManager assetManager = getAssets();
                try {
                    InputStream inputStream = assetManager.open("images/"+imageName);
                    holder.imageName.setImageBitmap(BitmapFactory.decodeStream(inputStream));
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            return view;
        }

PlayGame Class

PlayGame class covers the main logic of the game. Each quiz question is selected randomly and displayed by GenerateQuestionNumber and PopulateQuestion functions respectively.

//Generate Random Game Question Number
    private int GenerateQuestionNumber(){
        Random rand = new Random();
        int temp = -1;
        boolean test;
        do{
            temp = rand.nextInt(totalQuestions);
            test = myListOfTriviaQuestions.get(temp).GetIsThisQuestionAsked();
            if(!test){
                myListOfTriviaQuestions.get(temp).SetIsThisQuestionAsked(true);
                questionsAsked+=1;
                sequenceOfQuestionsAsked[indexOfsequenceOfQuestionsAsked++]=temp;
                break;
            }
        }while(test && questionsAsked < totalQuestions);    //skip while new

        return temp;//return currentQuestionNumber+=1;
    }


//Populate UI controls with trivia game questions
    private void PopulateQuestion() {       
        if(questionsAsked<=myListOfTriviaQuestions.size()){ //true until last question
            questionNumber.setText("question " + questionsAsked);
            txtPoints.setText(String.valueOf(totalPoints));
            question.setText(myListOfTriviaQuestions.get(currentQuestionNumber).GetQuestion());
            optionOne.setText(myListOfTriviaQuestions.get(currentQuestionNumber).GetOptions().get(0));
            optionTwo.setText(myListOfTriviaQuestions.get(currentQuestionNumber).GetOptions().get(1));
            optionThree.setText(myListOfTriviaQuestions.get(currentQuestionNumber).GetOptions().get(2));
            optionFour.setText(myListOfTriviaQuestions.get(currentQuestionNumber).GetOptions().get(3));
        }else{  //game complete
            isGameEnded=true;
            EndGame();
            DisplayResults();
        }
    }

SecondCountDownRunner

SecondCountDownRunner is a custom runnable class to send timer message after each second to update game state.

private class SecondCountDownRunner implements Runnable{
        private boolean doRun = true;       

        public void run() {

            //Log.i("sec..","inside:"+doRun);
            while( doRun && !Thread.currentThread().isInterrupted()){
                Message m = new Message();
                m.what = PlayGame.SECONDPASSEDIDENTIFIER;   //unique message code
                PlayGame.this.myTimerViewUpdateHandler.sendMessage(m);
                try {
                    Thread.sleep(1000);             
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            }

        }

        //To stop timer
        public void stopThread(){
            doRun=false;
        }

        //To resume timer
        public void resumeThread(){
            doRun=true;
        }

        public void startThread(){
            doRun=true;
        }
    }

myTimerViewUpdateHandler class does handle message from above runnable to perform desired state change of the game.
Handler myTimerViewUpdateHandler = new Handler(){

        @Override
        public void handleMessage(Message msg) {
            switch(msg.what){
                case PlayGame.SECONDPASSEDIDENTIFIER:
                    if(mySecondsPassed > 0)
                        mySecondsPassed -= 1;
                    else {
                        mySecondsPassed = config.GetTimeToAnswer();
                        incorrect+=1;
                        if(questionsAsked >= totalQuestions){   //true when all questions asked
                            isGameEnded=true;
                            EndGame();
                            DisplayResults();
                        }
                        else {
                        currentQuestionNumber=GenerateQuestionNumber();
                        PopulateQuestion();
                        }
                    }

                    UpdateTimerColors(mySecondsPassed);
            }
            super.handleMessage(msg);
    }

  };

Result Class

Result class simply displays results the statistics received from PlayGame class.

Intent resultReview = getIntent();      
        totalPoints = resultReview.getExtras().getInt("Points");
        title = resultReview.getStringExtra("Title");
        txtTitle.setText(title);

        prefs = PreferenceManager.getDefaultSharedPreferences(this);

        highScore = prefs.getInt(title + "HS", -1);

        if(highScore == -1){
            SharedPreferences.Editor prefsEditor = prefs.edit();
            prefsEditor.putInt(title + "HS", totalPoints);
            prefsEditor.commit();

            txtHighScore.setText("");
            txtYourScore.setText("With " + totalPoints + " points you have set an new High score!");
        }else{
            if(highScore > totalPoints){
                txtHighScore.setText("Highscore: " + highScore);
                txtYourScore.setText("You have scored " + totalPoints + " points.");
            }else{
                SharedPreferences.Editor prefsEditor = prefs.edit();
                prefsEditor.putInt(title + "HS", totalPoints);
                prefsEditor.commit();

                txtHighScore.setText("");
                txtYourScore.setText("With " + totalPoints + " points you have set an new High score!");
            }
        }

P-list Configuration:

Project includes quizzeslist.plist file that stores data about annotations. Each <quiz/> item defines one quiz in collection of quizzes. Each quiz has a name, description, imageName and list of questions with their answers. Questions has array of <question/> child items. Each <question/> item has a question, array of options and an answer. These are the annotations taken from plist file:

• Name – of quiz • Description – about quiz • ImageName – of the quiz logo • Questions – in a quiz. • Question – in a quiz. • Options – in a question • Answer – of a question

<plist version="1.0">
<dict>
    <quiz>          
        <key>Name</key>
        <string>History</string>
        <key>Description</key>
        <string>Check your knowledge about great historical events, who did what where to whom!</string>
        <key>ImageName</key>
        <string>history_icon.png</string>
        <questions>
            <question>
                <key>Question</key>
                <string>Which book is NOT part of the Standard Works?</string>
                <key>Options</key>
                <array>
                    <string>The Book of Mormon</string>
                    <string>Lectures on Faith</string>
                    <string>Bible</string>
                    <string>Doctrine and Covenants</string>
                </array>
                <key>Answer</key>
                <integer>2</integer>
            </question>
            <question>
                <key>Question</key>
                <string>Who is NOT a member of the God-head?</string>
                <key>Options</key>
                <array>             
                    <string>Joseph Smith</string>
                    <string>Jesus Christ</string>
                    <string>The Holy Ghost</string>
                    <string>Heavenly Father</string>
                </array>
                <key>Answer</key>
                <integer>1</integer>
            </question>
            <question>
                <key>Question</key>
                <string>The First Vision took place in which year?</string>
                <key>Options</key>
                <array>
                    <string>1820</string>
                    <string>1830</string>
                    <string>1800</string>
                    <string>1776</string>
                </array>
                <key>Answer</key>
                <integer>1</integer>
            </question>         
        </questions>    
    </quiz>
</dict> 
</plist>
22 Comments Leave a comment