Skip to main content
A SIMPLE ANDROID QUIZ APP

Android Game Tutorial

Android Game Tutorial

A very very simple android game using SQLite database.

What the application will be doing is :

  • A timer of 1 minute
  • 20 Questions
  • A questions bank class
  • Three buttons for showing options
  • And a good looking UI. Hope you like.

my game

Hey please comment below about what do you think about this post and my work. I do appreciate your time you spend reading my post.

So make a new android application in android studio and name it whatever you want to name it. I named it A simple game.

DESIGNING PART : 

Open your activity_main.xml file [res > layout > activity_main.xml ] and edit it as :

activity_main.xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:ads="http://schemas.android.com/apk/res-auto"
 android:id="@+id/relatively"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:background="#d15400"
 android:orientation="vertical"
 android:weightSum="1" >
 <LinearLayout
 android:id="@+id/linearLayout1"
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:layout_weight="0.90"
 android:orientation="vertical"
 android:weightSum="1" >
 <LinearLayout
 android:id="@+id/linearLayout11"
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:layout_weight="0.20"
 android:orientation="vertical"
 android:weightSum="1" >
 <LinearLayout
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:layout_weight="1"
 android:orientation="horizontal" >
 <TextView
 android:id="@+id/score"
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:layout_centerHorizontal="true"
 android:layout_gravity="center"
 android:layout_marginRight="10dp"
 android:layout_weight="1"
 android:gravity="center"
 android:text="Score : 1"
 android:textColor="#ffffff"
 android:textSize="25.0sp"
 android:textStyle="bold" />
 <TextView
 android:id="@+id/timers"
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:layout_centerHorizontal="true"
 android:layout_gravity="center"
 android:layout_marginRight="10dp"
 android:layout_weight="1"
 android:gravity="center"
 android:text="00:00:49"
 android:textColor="#ffffff"
 android:textSize="25.0sp"
 android:textStyle="bold" />
 </LinearLayout>
 </LinearLayout>
 <LinearLayout
 android:id="@+id/linearLayout12"
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:layout_weight="0.60"
 android:orientation="vertical"
 android:weightSum="1" >
 <LinearLayout
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:layout_weight="0.40" >
 <TextView
 android:id="@+id/txtQuestion"
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:layout_centerHorizontal="true"
 android:layout_gravity="center"
 android:layout_marginTop="5dp"
 android:gravity="center"
 android:text="15*2*1-1"
 android:textColor="#ffffff"
 android:textSize="35.0sp"
 android:textStyle="bold" />
 </LinearLayout>
 <LinearLayout
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:layout_weight="0.20"
 android:orientation="vertical"
 android:weightSum="1" >
 <Button
 android:id="@+id/button1"
 android:layout_width="fill_parent"
 android:layout_height="wrap_content"
 android:layout_gravity="center"
 android:layout_marginLeft="80dp"
 android:layout_marginRight="80dp"
 android:layout_marginTop="5dp"
 android:background="#fff"
 android:gravity="center"
 android:text="30"
 android:textColor="#000000"
 android:textSize="25.0sp" />
 <Button
 android:id="@+id/button2"
 android:layout_width="fill_parent"
 android:layout_height="wrap_content"
 android:layout_gravity="center"
 android:layout_marginLeft="80dp"
 android:layout_marginRight="80dp"
 android:layout_marginTop="5dp"
 android:background="#fff"
 android:gravity="center"
 android:text="29"
 android:textColor="#000000"
 android:textSize="25.0sp" />
 <Button
 android:id="@+id/button3"
 android:layout_width="fill_parent"
 android:layout_height="wrap_content"
 android:layout_gravity="center"
 android:layout_marginLeft="80dp"
 android:layout_marginRight="80dp"
 android:layout_marginTop="5dp"
 android:background="#fff"
 android:gravity="center"
 android:text="32"
 android:textColor="#000000"
 android:textSize="25.0sp" />
 </LinearLayout>
 </LinearLayout>
 </LinearLayout>
</LinearLayout>

Make another xml file with name activity_result.xml and edit it as following :

activity_result.xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:background="#2a3f4c"
 android:orientation="vertical"
 android:layout_centerInParent="true"
 >
 <TextView
 android:id="@+id/textResult"
 android:layout_width="match_parent"
 android:layout_gravity="center"
 android:layout_marginTop="50dp"
 android:layout_height="wrap_content"
 android:text="Large Text"
 android:textColor="#ffffff"
 android:textSize="20sp"
 android:padding="10dp"
 android:textStyle="bold" />
 <Button
 android:id="@+id/btn"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:background="#000000"
 android:layout_marginTop="50dp"
 android:padding="20dp"
 android:layout_gravity="center"
 android:onClick="playagain"
 android:text="PLAY AGAIN"
 android:textColor="#ffffff"
 android:textSize="20sp"/>

</LinearLayout>

OK design part is  done (as simple as that).

CODING PART :

There are four class files :

    • Question.java
    • QuestionActivity.java
    • QuizHelper.java
    • ResultActivity.java

Make it and edit all of them as below.

Question.java

package hitesh.asimplegame;

import android.app.Activity;

public class Question extends Activity {

	private int ID;
	private String QUESTION;
	private String OPTA;
	private String OPTB;
	private String OPTC;

	private String ANSWER;

	public Question() {
		ID = 0;
		QUESTION = "";
		OPTA = "";
		OPTB = "";
		OPTC = "";

		ANSWER = "";

	}

	public Question(String qUESTION, String oPTA, String oPTB, String oPTC,
			String aNSWER) {
		QUESTION = qUESTION;
		OPTA = oPTA;
		OPTB = oPTB;
		OPTC = oPTC;

		ANSWER = aNSWER;

	}

	public int getID() {
		return ID;
	}

	public String getQUESTION() {
		return QUESTION;
	}

	public String getOPTA() {
		return OPTA;
	}

	public String getOPTB() {
		return OPTB;
	}

	public String getOPTC() {
		return OPTC;
	}

	public String getANSWER() {
		return ANSWER;
	}

	public void setID(int id) {
		ID = id;
	}

	public void setQUESTION(String qUESTION) {
		QUESTION = qUESTION;
	}

	public void setOPTA(String oPTA) {
		OPTA = oPTA;
	}

	public void setOPTB(String oPTB) {
		OPTB = oPTB;
	}

	public void setOPTC(String oPTC) {
		OPTC = oPTC;
	}

	public void setANSWER(String aNSWER) {
		ANSWER = aNSWER;
	}

}

QuestionActivity.java


package hitesh.asimplegame;

/**
 * Created by H on 7/12/2015.
 */

import java.util.List;
import java.util.Timer;
import java.util.concurrent.TimeUnit;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Typeface;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class QuestionActivity extends Activity {
    List<Question> quesList;
    int score = 0;
    int qid = 0;

    Question currentQ;
    TextView txtQuestion, times, scored;
    Button button1, button2, button3;

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

        QuizHelper db = new QuizHelper(this);  // my question bank class
        quesList = db.getAllQuestions();  // this will fetch all quetonall questions
        currentQ = quesList.get(qid); // the current question

        txtQuestion = (TextView) findViewById(R.id.txtQuestion);
        // the textview in which the question will be displayed

        // the three buttons,
        // the idea is to set the text of three buttons with the options from question bank
        button1 = (Button) findViewById(R.id.button1);
        button2 = (Button) findViewById(R.id.button2);
        button3 = (Button) findViewById(R.id.button3);

        // the textview in which score will be displayed
        scored = (TextView) findViewById(R.id.score);

        // the timer
        times = (TextView) findViewById(R.id.timers);

        // method which will set the things up for our game
        setQuestionView();
        times.setText("00:02:00");

        // A timer of 60 seconds to play for, with an interval of 1 second (1000 milliseconds)
        CounterClass timer = new CounterClass(60000, 1000);
        timer.start();

        // button click listeners
        button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                // passing the button text to other method
                // to check whether the anser is correct or not
                // same for all three buttons
                getAnswer(button1.getText().toString());
            }
        });

        button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getAnswer(button2.getText().toString());
            }
        });

        button3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getAnswer(button3.getText().toString());
            }
        });
    }

    public void getAnswer(String AnswerString) {
        if (currentQ.getANSWER().equals(AnswerString)) {

            // if conditions matches increase the int (score) by 1
            // and set the text of the score view
            score++;
            scored.setText("Score : " + score);
        } else {

            // if unlucky start activity and finish the game

            Intent intent = new Intent(QuestionActivity.this,
                    ResultActivity.class);

            // passing the int value
            Bundle b = new Bundle();
            b.putInt("score", score); // Your score
            intent.putExtras(b); // Put your score to your next
            startActivity(intent);
            finish();
        }
        if (qid < 20) {

            // if questions are not over then do this
            currentQ = quesList.get(qid);
            setQuestionView();
        } else {

            // if over do this
            Intent intent = new Intent(QuestionActivity.this,
                    ResultActivity.class);
            Bundle b = new Bundle();
            b.putInt("score", score); // Your score
            intent.putExtras(b); // Put your score to your next
            startActivity(intent);
            finish();
        }

    }

    @TargetApi(Build.VERSION_CODES.GINGERBREAD)
    @SuppressLint("NewApi")
    public class CounterClass extends CountDownTimer {

        public CounterClass(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
            // TODO Auto-generated constructor stub
        }

        @Override
        public void onFinish() {
            times.setText("Time is up");
        }

        @Override
        public void onTick(long millisUntilFinished) {
            // TODO Auto-generated method stub

            long millis = millisUntilFinished;
            String hms = String.format(
                    "%02d:%02d:%02d",
                    TimeUnit.MILLISECONDS.toHours(millis),
                    TimeUnit.MILLISECONDS.toMinutes(millis)
                            - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS
                            .toHours(millis)),
                    TimeUnit.MILLISECONDS.toSeconds(millis)
                            - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS
                            .toMinutes(millis)));
            System.out.println(hms);
            times.setText(hms);
        }

    }

    private void setQuestionView() {

        // the method which will put all things together
        txtQuestion.setText(currentQ.getQUESTION());
        button1.setText(currentQ.getOPTA());
        button2.setText(currentQ.getOPTB());
        button3.setText(currentQ.getOPTC());

        qid++;
    }

}

QuizHelper.java

package hitesh.asimplegame;

import java.util.ArrayList;
import java.util.List;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class QuizHelper extends SQLiteOpenHelper {
	private static final int DATABASE_VERSION = 1;
	// Database Name
	private static final String DATABASE_NAME = "mathsone";
	// tasks table name
	private static final String TABLE_QUEST = "quest";
	// tasks Table Columns names
	private static final String KEY_ID = "qid";
	private static final String KEY_QUES = "question";
	private static final String KEY_ANSWER = "answer"; // correct option
	private static final String KEY_OPTA = "opta"; // option a
	private static final String KEY_OPTB = "optb"; // option b
	private static final String KEY_OPTC = "optc"; // option c

	private SQLiteDatabase dbase;

	public QuizHelper(Context context) {
		super(context, DATABASE_NAME, null, DATABASE_VERSION);
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		dbase = db;
		String sql = "CREATE TABLE IF NOT EXISTS " + TABLE_QUEST + " ( "
				+ KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + KEY_QUES
				+ " TEXT, " + KEY_ANSWER + " TEXT, " + KEY_OPTA + " TEXT, "
				+ KEY_OPTB + " TEXT, " + KEY_OPTC + " TEXT)";
		db.execSQL(sql);
		addQuestion();
		// db.close();
	}

	private void addQuestion() {
		Question q1 = new Question("5+2 = ?", "7", "8", "6", "7");
		this.addQuestion(q1);
		Question q2 = new Question("2+18 = ?", "18", "19", "20", "20");
		this.addQuestion(q2);
		Question q3 = new Question("10-3 = ?", "6", "7", "8", "7");
		this.addQuestion(q3);
		Question q4 = new Question("5+7 = ?", "12", "13", "14", "12");
		this.addQuestion(q4);
		Question q5 = new Question("3-1 = ?", "1", "3", "2", "2");
		this.addQuestion(q5);
		Question q6 = new Question("0+1 = ?", "1", "0", "10", "1");
		this.addQuestion(q6);
		Question q7 = new Question("9-9 = ?", "0", "9", "1", "0");
		this.addQuestion(q7);
		Question q8 = new Question("3+6 = ?", "8", "7", "9", "9");
		this.addQuestion(q8);
		Question q9 = new Question("1+5 = ?", "6", "7", "5", "6");
		this.addQuestion(q9);
		Question q10 = new Question("7-5 = ?", "3", "2", "6", "2");
		this.addQuestion(q10);
		Question q11 = new Question("7-2 = ?", "7", "6", "5", "5");
		this.addQuestion(q11);
		Question q12 = new Question("3+5 = ?", "8", "7", "5", "8");
		this.addQuestion(q12);
		Question q13 = new Question("0+6 = ?", "7", "6", "5", "6");
		this.addQuestion(q13);
		Question q14 = new Question("12-10 = ?", "1", "2", "3", "2");
		this.addQuestion(q14);
		Question q15 = new Question("12+2 = ?", "14", "15", "16", "14");
		this.addQuestion(q15);
		Question q16 = new Question("2-1 = ?", "2", "1", "0", "1");
		this.addQuestion(q16);
		Question q17 = new Question("6-6 = ?", "6", "12", "0", "0");
		this.addQuestion(q17);
		Question q18 = new Question("5-1 = ?", "4", "3", "2", "4");
		this.addQuestion(q18);
		Question q19 = new Question("4+2 = ?", "6", "7", "5", "6");
		this.addQuestion(q19);
		Question q20 = new Question("5+1 = ?", "6", "7", "5", "6");
		this.addQuestion(q20);
		Question q21 = new Question("5-4 = ?", "5", "4", "1", "1");
		this.addQuestion(q21);
		// END
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldV, int newV) {
		// Drop older table if existed
		db.execSQL("DROP TABLE IF EXISTS " + TABLE_QUEST);
		// Create tables again
		onCreate(db);
	}

	// Adding new question
	public void addQuestion(Question quest) {
		// SQLiteDatabase db = this.getWritableDatabase();
		ContentValues values = new ContentValues();
		values.put(KEY_QUES, quest.getQUESTION());
		values.put(KEY_ANSWER, quest.getANSWER());
		values.put(KEY_OPTA, quest.getOPTA());
		values.put(KEY_OPTB, quest.getOPTB());
		values.put(KEY_OPTC, quest.getOPTC());

		// Inserting Row
		dbase.insert(TABLE_QUEST, null, values);
	}

	public List<Question> getAllQuestions() {
		List<Question> quesList = new ArrayList<Question>();
		// Select All Query
		String selectQuery = "SELECT  * FROM " + TABLE_QUEST;
		dbase = this.getReadableDatabase();
		Cursor cursor = dbase.rawQuery(selectQuery, null);
		// looping through all rows and adding to list
		if (cursor.moveToFirst()) {
			do {
				Question quest = new Question();
				quest.setID(cursor.getInt(0));
				quest.setQUESTION(cursor.getString(1));
				quest.setANSWER(cursor.getString(2));
				quest.setOPTA(cursor.getString(3));
				quest.setOPTB(cursor.getString(4));
				quest.setOPTC(cursor.getString(5));

				quesList.add(quest);
			} while (cursor.moveToNext());
		}
		// return quest list
		return quesList;
	}

}

ResultActivity.java

package hitesh.asimplegame;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;

import android.view.View;
import android.widget.TextView;

public class ResultActivity extends Activity {

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

		TextView textResult = (TextView) findViewById(R.id.textResult);

		Bundle b = getIntent().getExtras();

		int score = b.getInt("score");

        textResult.setText("Your score is " + " " + score + ". Thanks for playing my game.");

	}

	public void playagain(View o) {

			Intent intent = new Intent(this, QuestionActivity.class);

			startActivity(intent);

	}
}

And last but not the least AndroidManifest.xml


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="hitesh.asimplegame" >

    <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" >
        <activity android:name=".QuestionActivity" android:label="@string/app_name" android:screenOrientation="portrait">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".ResultActivity" android:label="@string/app_name" android:screenOrientation="portrait"/>

    </application>

</manifest>

my game

 

You can download the source using this link : A simple game
If have any questions, feel free the question below.
Also, here’s a another link explaining making a complete game with Splash screen, Users menu and other functions.

game2 (3)

 

Hey please comment below about what do you think about this post and my work. I do appreciate your time you spend reading my post…..

  • Pingback: Android JSON Parsing • ParallelCodes()

  • Pingback: Connect Android to MS SQL Database. • ParallelCodes()

  • Martin Park

    I would like to use some of this code as part of an app that I am writing for research. What would be the procedure to follow for the licence or so to use some of this code and change it to my preferences?

    • Thanks Martin for the interest, But you can use the code its free

      • ncutiga

        wowww! that’s great! i have same idea, me too i want to use it in my app!
        thank you so much, your work is really helpful! GBU

  • DisQ SteeZ

    How do I make the game random, atm it just repeating the questions in same order.

  • Patrick Bayani

    I got some errors. Here it is. Hope you can help me sir.
    In QuestionActivity.java i got this errors:
    “Cannot resolve symbol ‘Question'”
    “Cannot resolve symbol ‘R'”
    “Cannot resolve method ‘getANSWER()'”
    “Cannot resolve method ‘getQUESTION'”

    In QuizHelper.java same as in QuestionActivity.java
    In ResultActivity.java:
    “Cannot resolve symbol ‘R'”

    Hope you can help me. I’m new at Android Studio.
    Sorry for my english. Hope you can help me. TIA!

    • Just clean the project the error must go. If not, see whether or not you have mistakes in the res folder’s files and xml.

  • 915503

    Awesome tutorial, helped me a lot!! I’m stumbling upon one problem though. I’d like to save and show the elapsed time in the result activity. Do you know a good method?

  • Katy

    Hi Thankyou for this, I was trying to add a menu page before you start the quiz (where you click a button then the quiz will start) I was wondering if you would be able to help. Thank you.

  • Erick David NH

    Hey man! Can you help me with a project? Is something like this, but different, I need the code for a quiz with radiobuttons and radiogroups, but I don’t understand how. I have 5 questions and 4 answers for any question, I need the application evaluates the answers and display the result. Please 🙁

    • I will help you Erick just give me two-three days

      • Erick David NH

        Of course! Thank you very much!

        • Hey Erick Hi.. sorry I’m late but I was busy ..here it is
          http://www.parallelcodes.com/android-game-tutorial-part-2-using-radio-buttons/

          • Samson Tesfaye

            I am learning a lot from your post on sql server using android.I am able to connect retrive, insert, update and delete data into sql over WiFi network. Now I need you help me how to use scope identity to insert results based on primary key of first table.just for one to many relations.

  • Mihai ION

    Hi,
    I want to make a similar quiz game, with at least one correct answer, where it is considered correct response only if all correct answers are selected. Can you give me some help? Thanks.

  • Mutua

    Hey. Thanks for this awesome sample. I would appreciate if you posted code for getting quiz questions from SQL Server database. Thanks in advance.

  • Muhammad Hasan

    Hey ! Great work,,, I tried this app but the thing is that timer isn’t working… App should stop and go to the score page when the timer is ended. ??? any solution?

    Regards!

  • Shane Bell

    some of the files have errors. I need help. Not working for me!

    • what errors are you getting?

      • Shane Bell

        I figured them out. However i need to make some modification to the code. Could you help me?

        • What help u need shane?

          • Shane Bell

            Ok so i’m pretty new to Android Studio. I am developing an app for a school project. The quiz app you provided is great and i want to add a menu, a splash screen, and a untimed section. Can that be done?

          • Yeah it can be definitely done.

          • Shane Bell

            I was trying to add a menu but no luck. Usually i would start my menu from the main_Activity. However i wasn’t able to do with your code.
            I definitely need your assistance to pull this off.

          • Ok I will post about it in one or two days…I hope its not urgent!

          • Shane Bell

            Well actually it is. I know its probably not fair for me to ask this on such a short notice. But if i have to wait i will because i need your help. As soon as possible will be gratefully appreciated.

          • Ok I will try my best.

          • Shane Bell

            Thank you Hitesh

  • ozzy

    Hi,

    I need some help regarding this code, if possible could I have your email address?

  • Humairah

    broo ,,when i add one answer button then all the required component ,the app has been forced close

  • Krishna Patel

    Hello ,
    thanks for your help but i’m searching for the logo quiz Android Application.
    Can you please provide the source code of simple logo quiz ? i’m bit confused how to do it..:)

    • Mike

      Did you find a tutorial about a logo quiz game ?
      I am searching for one too.

  • Novelina Aulia Harmaylin

    helo, thank you so much to post this cool content, right now i do my final project in school, make quiz application with android. May I ask you, do you make this app with android studio or eclipse? I hope you answer my questions becuse i use android studio.

    • I made it in Android Studio but you can use both

      • Novelina Aulia Harmaylin

        thank you for your answer and it’s really work, but if i choose the wrong answer the timer is still going, how to make it stop when the answer is false? thank you so much 🙂

  • yahyaoui jasser

    hello ,

    how can I change your questions by mine !!?? this is my problem … help please

    • Just replace the questions in the QuizHelper.java activity.

      • Srishti Raj

        I changed the questions in QuizHelper.java but when i run it, it still shows the old questions
        why why why

        • Johnson Mizzy Dubula

          un install the app and re install it, it will create a new table with new questions

  • Nidhin Kumar

    Hitesh i have some quiz questions which is in .csv format is it possible to use this in sqlite if so is there tutorials or steps to convert those .csv files to sqlite

  • Srishti Raj

    idk why but its not working
    as soon as i run the code, it opens for a second in my phone and then closes.
    what could be the reason for this?
    i copied the exact code

  • Srishti Raj

    I changed the questions but it still shows the old questions
    why why why

    • Its simple the code says Create table if not exists… you have to uninstall or clear data of the application if its already installed on your phone

      • Srishti Raj

        thank you so much
        this worked

  • Johnson Mizzy Dubula

    instead of using numbers can i use alphabets? i am asking because i do not see an array for answers

  • Ehab Obiad

    Thank you, it’s amazing, I just want to give the user other chance or whatever was the answer just complete all of the question and then see the score page and shows the correct and wrong answer ??? is that easy ??

  • Rupesh Gurung

    Every time I click a button, instead of going to another question it goes on the result activity. Get back soon please Hitesh Vikani

    • You have to press the right question for going to next question. Or else you have not given the questions properly in the DB.

  • Rimsy O

    how can i randomize the question()?

    • Jason Bayonito

      String selectQuery = “SELECT * FROM ” + TABLE_QUEST + ” ORDER BY RANDOM()”;

      • Frantzky Fatal

        Where i should put those codes ?

        • Jason Bayonito

          Replace the Query in QiuzHelper.java

  • Christopher Ilofo

    every time i choose an option on the first question , it doesnt show the next question. how can i fix it ?
    it keeps on showing the same question

  • Bakr Hussein

    hi i changed the questions and the answers but it’s still showing the old ones

    • Please clear the database or uninstall the application and reinstall it

      • ayesha

        i like your work

  • Sahil

    Hello sir i try it so good but one problem found. I correct all answer it is good but unfortunately any wrong answer quiz is finished. any procedure is any wrong answer show your answer is wrong 1 point loss and continue the game

    • else {

      // if unlucky start activity and finish the game

      Intent intent = new Intent(QuestionActivity.this,
      ResultActivity.class);

      // passing the int value
      Bundle b = new Bundle();
      b.putInt(“score”, score); // Your score
      intent.putExtras(b); // Put your score to your next
      startActivity(intent);
      finish();
      }
      Replace line number 100 (else loop in QuestionActivity.java) with this code :

      score–;
      scored.setText(“Score : ” + score);

      • amira elsayed

        plz can you tell me what is in line 100 to change it ,also i have another question when time out i make it go to result page and say score and play again the problem is i dont solve any one and it give me score 2 why

      • Paweł Lewiński

        Hello Hitesh, very good tutorial. One question not to stop the game and not to go to ResultActivity when the answer is wrong? I made it count “-1” as you advised would like the game to continue until end of the time. Thanks in advance 4 answer, I appreciate your time.

      • Karan Bhatia

        Hello sir i do not understand which line delete and replace pls some explain more. You mention replace 100 line. i do not understand in 100 line what is write. Pls help me. I want quiz continue work if user wrong answer. Thankyou

  • Sreeman Rao Juvvadi

    how to generate the given questions in the sqlite database randomly i mean not in the sequential order..

    • You will have to use some logic to generate random int value and than fetch the question from its ID

  • Neo

    You have created a simple app with only 20 questions. But If I want to create a quiz game with several hundred questions, Do I have another method or this method is relevant?

    • This is relevant, has I made a game of 6 levels (math based) about a year and a half (in 2014) ago and also published it on google play. And I learnt this code at that time. But there are so many improvements that can be done in this code. For example I’m making a new variable for every new question instead you can make a question variable once and use it, it will be much faster.
      Question q1 = //question definition
      db.add(q1);
      q1 = //another question definition
      db.add(q1);
      And other such minor improvement can be done

  • Neo

    I want to create a quiz game with some topics as ‘History of USA’ , ‘Football’ , ‘Geography’ etc. When user clicks,for example ‘Geography’, my app has to show question and options of this topic. How can it be done? In other words, how to show to user questions of certain topic?

    • You can easily do this. You can create different classes (i.e. Database classes) for different topics or You can add a category field in the above class and fetch questions accordingly.

      • Abdi Ganamo

        Excuse me! I am not clear with your answer. How I can add another tables and classes?

  • Moh-Al

    Hi Hitesh and thanks for the codes but i would like to have a user choose a button to go to the next question or finish when they choose rather than the app doing it automatically. , thanks

    • You will have to implement the next question logic by taking two buttons Next and Previous respectively.
      On button click listener of next button write :
      currentQ = quesList.get(qid);
      setQuestionView();
      where qid will be +1 question id of the current question ID and vice versa for the previous question

  • Raksha Bumb

    Hi Hitesh,thank u for the codes but i have error in QuizHelper.getAllQuestions(QuizHelper.java:103) and MainActivity.onCreate(MainActivity.java:39) Please help to solve this error

    • Please show your code’s logcat error output

      • Raksha Bumb

        {at com.example.siddharth.quiz.QuizHelper.getAllQuestions(QuizHelper.java:103)
        at com.example.siddharth.quiz.MainActivity.onCreate(MainActivity.java:39)}this shown in logcat error output

        • Uninstall the application and reinstall it, the error is occurring because the db is already present which can’t be upgraded.

      • Raksha Bumb

        at android.database.sqlite.SQLiteCompiledSql.native_compile(Native Method)
        at android.database.sqlite.SQLiteCompiledSql.(SQLiteCompiledSql.java:68)
        at android.database.sqlite.SQLiteProgram.compileSql(SQLiteProgram.java:134)
        at android.database.sqlite.SQLiteProgram.compileAndbindAllArgs(SQLiteProgram.java:361)
        at android.database.sqlite.SQLiteStatement.acquireAndLock(SQLiteStatement.java:260)
        at android.database.sqlite.SQLiteStatement.executeUpdateDelete(SQLiteStatement.java:84)
        at android.database.sqlite.SQLiteDatabase.executeSql(SQLiteDatabase.java:2021)
        at android.database.sqlite.SQLiteDatabase.execSQL(SQLiteDatabase.java:1961)
        at com.example.siddharth.quiz.QuizHelper.onCreate(QuizHelper.java:36)
        at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:165)
        at android.database.sqlite.SQLiteOpenHelper.getReadableDatabase(SQLiteOpenHelper.java:231)
        at com.example.siddharth.quiz.QuizHelper.getAllQuestions(QuizHelper.java:103)
        at com.example.siddharth.quiz.MainActivity.onCreate(MainActivity.java:39)
        at android.app.Activity.performCreate(Activity.java:4470)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1053)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1934)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1995)
        at android.app.ActivityThread.access$600(ActivityThread.java:128)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1161)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:137)
        at android.app.ActivityThread.main(ActivityThread.java:4517)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:511)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:993)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:760)
        at dalvik.system.NativeStart.main(Native Method)
        06-29 10:23:04.840 21616-21616/com.example.siddharth.quiz E/AndroidRuntime: FATAL EXCEPTION: main
        java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.siddharth.quiz/com.example.siddharth.quiz.MainActivity}: android.database.sqlite.SQLiteException: Can’t upgrade read-only database from version 0 to 1: /data/data/com.example.siddharth.quiz/databases/mathsone
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1970)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1995)
        at android.app.ActivityThread.access$600(ActivityThread.java:128)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1161)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:137)
        at android.app.ActivityThread.main(ActivityThread.java:4517)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:511)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:993)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:760)
        at dalvik.system.NativeStart.main(Native Method)
        Caused by: android.database.sqlite.SQLiteException: Can’t upgrade read-only database from version 0 to 1: /data/data/com.example.siddharth.quiz/databases/mathsone
        at android.database.sqlite.SQLiteOpenHelper.getReadableDatabase(SQLiteOpenHelper.java:244)
        at com.example.siddharth.quiz.QuizHelper.getAllQuestions(QuizHelper.java:103)
        at com.example.siddharth.quiz.MainActivity.onCreate(MainActivity.java:39)
        at android.app.Activity.performCreate(Activity.java:4470)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1053)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1934)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1995)
        at android.app.ActivityThread.access$600(ActivityThread.java:128)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1161)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:137)
        at android.app.ActivityThread.main(ActivityThread.java:4517)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:511)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:993)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:760)

  • Big Boss

    I didn’t understand how this application know the correct answer, in the source code there is no field contain the right answer for every question !

    • Mon Dher

      No body can answer my question ? where correct answer is stored?

      • public Question(String qUESTION, String oPTA, String oPTB, String oPTC,
        String aNSWER) {
        QUESTION = qUESTION;
        OPTA = oPTA;
        OPTB = oPTB;
        OPTC = oPTC;

        ANSWER = aNSWER;

        }
        ______________________________________________________
        Question q7 = new Question(“9-9 = ?”, “0”, “9”, “1”, “0”);
        this.addQuestion(q7);
        ______________________________________________________
        Question q20 = new Question(“5+1 = ?”, “6”, “7”, “5”, “6”);
        this.addQuestion(q20);
        ______________________________________________________
        Question q21 = new Question(“5-4 = ?”, “5”, “4”, “1”, “1”);
        this.addQuestion(q21);
        ______________________________________________________
        So every 5th string is your answer

        • Mon Dher

          thank you bro

  • Tee

    Hi… thank you so much for this code. I’m a learner and this code was so much helpful for me. But I have a question. … if I want to redirect to result activity when time period is over, no matter all questions are attempted or not, how that would be possible?
    In this code, we can go to result page only when all questions are attempted.
    Thank you in advance 🙂

    • in the timer finish method write
      Intent intent = new Intent(QuestionActivity.this,
      ResultActivity.class);
      Bundle b = new Bundle();
      b.putInt(“score”, score); // Your score
      intent.putExtras(b); // Put your score to your next
      startActivity(intent);
      finish();

      • Tee

        Yes…I tried it. But now the problem is . ..if I click on ‘play again’ button , in the question section simultaneously two timer is running. .one, the previous remaining timer in background and second, current timer. As a result, when previously running timer comes to 0, result activity popping up, showing previous result and for current timer result activity again comes with new result. Couldn’t solve it…tried timer.cancel(). It still in same situation..

  • Pingback: Android Import excel into Sqlite Database()

  • Karan Bhatia

    Hello Sir i create one app for kids. this quiz i used in my app or not please tell me. Thanks

    • you can use this source code.

      • Karan Bhatia

        Thanks Sir

  • Sushant Kaushal

    i want to insert image in place of your question can u help me

  • Kathleen Seagan

    Why I can’t click the button for answer? Thanks 🙂

    • You might have mistakes in code, please check. Its not possible.

      • Kathleen Seagan

        I have this application and when I transfer your code to mine the buttons are not clickable and the question that pops up is the question that was design in the activity_main.xml. Thanks for your help 🙂

        • Can you post your code here

          • Kathleen Seagan

            what code? Because as far as I know I just copy your code to my application the difference is that I change the question and answer. When I made another project and only the activity above was made and paste your code to it, it works. May I have your email address so I can send to you my whole application code so you can what was my mistake?

  • Raksha Bumb

    i got error on this code line currentQ = quesList.get(qid); // the current question pls help to solve this problem.

    • Sankalp Upadhyay

      uninstall your app and clean project and run again…

  • ralf

    Hi, why i can’t click the button in main activity ? thanks for response

  • AKShrestha

    how can i generate the number randomly? can any one help me…
    thanks in advnace.

    • Paweł Lewiński

      Yeah, I also try/want this question to show randomly. Any support is more then appreciated

      • Jason Bayonito

        Replace this Query in QiuzHelper.java

        String selectQuery = “SELECT * FROM ” + TABLE_QUEST + ” ORDER BY RANDOM()”;

  • Eri Yudi Sastrawan

    how to add question more than 20?

  • Love your quiz game.

  • Husnul Yaqin

    hi hitesh vikani,
    what i have to do if i want to use question from “string.xml”?? the anwer from string.xml too.. please help me

  • Paweł Lewiński

    Hi, I have an issue with timer – when user starts the game but exit it without finishing, the timer still runs in bacground and Game over screen popups when time is finished. I want timer to stop wotking when user click back button to go to main menu. I know it should be timer.cance() but can’t postition it nor make it working. Thanks for advice.

  • anees aziz

    showing 2 logos after apk installation.please fix this

  • pat

    how can I change the question?

  • Frantzky Fatal

    How can I change the order of the questions when the player choose to play again

  • ojie2k1

    Hello, I want to know why the data size under the settings keep on increasing.
    I downloaded this app to learn how to make app quiz. Everything is working except for the data size.

    Thanks for your help.

  • Sankalp Upadhyay

    QuizHelper db = new QuizHelper(this); // my question bank class
    quesList = db.getAllQuestion();
    currentQ = quesList.get(qid);
    i have error in this line
    currentQ = quesList.get(qid);

    • Sankalp Upadhyay

      anyone can reply me please………

      • Sankalp Upadhyay

        how can i start the game
        frst launcher screen is 15*2*1-1
        3 button but they dont have action

  • Sankalp Upadhyay

    QuizHelper db = new QuizHelper(this); // my question bank class
    quesList = db.getAllQuestion();
    currentQ = quesList.get(qid);
    i have error in this line
    currentQ = quesList.get(qid);
    java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0

  • Sankalp Upadhyay

    yesssss finalllyyyy its working…. thank you Hitesh vikani sir…

Shares