Pages

About

Pages - Menu

Ads 468x60px

Social Icons

Main Menu

Featured Posts

Friday 11 July 2014

A Simple Quiz Game in Andriod

Step 1: Create the Project

By this time I think you are familiar with the drill. Create a project with the desired configuration. I created mine with the following attributes:
Project Name: Triviality
Application Name: Triviality
Package Name: com.example.triviality
Android Version: Android 4.0 API Level17
Activity Name: QuizActivity

Step 2: Define a class from questions

I decided to define a separate class for questions because of a very important reason, it makes my job easy. Each time I need to refer a question, it is much easier to refer to an object than to a set of strings. So here is my class Question:

package com.example.triviality;
public class Question {
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;
}
}

Step 3: Create the database helper

As you can recall the database helper was introduced by me in my previous post here. My DB helper is a java file called QuizHelper. It contains functions to create the database and tables and insert questions. I do not need to update or delete new questions for now. The following code is for the db helper. I am passing it over quickly because I have already explained it in an earlier tutorial. So here is my class DbHelper.java

package com.example.triviality;
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 DbHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "triviaQuiz";
// tasks table name
private static final String TABLE_QUEST = "quest";
// tasks Table Columns names
private static final String KEY_ID = "id";
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 DbHelper(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);
addQuestions();
//db.close();
}
private void addQuestions()
{
Question q1=new Question("Which company is the largest manufacturer" +
" of network equipment?","HP", "IBM", "CISCO", "C");
this.addQuestion(q1);
Question q2=new Question("Which of the following is NOT " +
"an operating system?", "SuSe", "BIOS", "DOS", "B");
this.addQuestion(q2);
Question q3=new Question("Which of the following is the fastest" +
" writable memory?","RAM", "FLASH","Register","C");
this.addQuestion(q3);
Question q4=new Question("Which of the following device" +
" regulates internet traffic?",    "Router", "Bridge", "Hub","A");
this.addQuestion(q4);
Question q5=new Question("Which of the following is NOT an" +
" interpreted language?","Ruby","Python","BASIC","C");
this.addQuestion(q5);
}
@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;
}
public int rowcount()
{
int row=0;
String selectQuery = "SELECT  * FROM " + TABLE_QUEST;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
row=cursor.getCount();
return row;
}
}

Step 4: Add questions to database

I seperated the DB Helper and this part for your better understanding. I am adding them questions of the app in the DbHelper itself in the onCreate function. As you might recall this function is executed when the database is first created. So here is the modified onCreate()

public void onCreate(SQLiteDatabase 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);
Question q1=new Question("Which company is the largest manufacturer" +
" of network equipment?","HP", "IBM", "CISCO", "C");
this.addQuestion(q1);
Question q2=new Question("Which of the following is NOT " +
"an operating system?", "SuSe", "BIOS", "DOS", "B");
this.addQuestion(q2);
Question q3=new Question("Which of the following is the fastest" +
" writable memory?","RAM", "FLASH","Register","C");
this.addQuestion(q3);
Question q4=new Question("Which of the following device" +
" regulates internet traffic?",    "Router", "Bridge", "Hub","A");
this.addQuestion(q4);
Question q5=new Question("Which of the following is NOT an" +
" interpreted language?","Ruby","Python","BASIC","C");
this.addQuestion(q5);
db.close();
}

Step 5: The layout

The layout is going to be pretty simple, a question and its options will be displayed with a button for going forward. At the end of the quiz the result can be seen. I have used a rating widget for that purpose as you will see later.
For now here is the layout:
Layout



Pretty simple right? The XML is simple too. Take a look at activity_quiz.xml:

<RelativeLayout 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"
   tools:context=".QuizActivity" >
<LinearLayout
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:layout_alignParentBottom="true"
       android:layout_alignParentLeft="true"
       android:layout_alignParentRight="true"
       android:layout_alignParentTop="true"
       android:orientation="vertical" >
<TextView
           android:id="@+id/textView1"
           android:layout_width="match_parent"
           android:layout_height="wrap_content"
           android:text="Large Text"
           android:textAppearance="?android:attr/textAppearanceLarge" />
<RadioGroup
           android:id="@+id/radioGroup1"
           android:layout_width="match_parent"
           android:layout_height="wrap_content"
           android:layout_weight="0.04" >
<RadioButton
               android:id="@+id/radio0"
               android:layout_width="match_parent"
               android:layout_height="wrap_content"
               android:checked="true"
               android:text="RadioButton" />
<RadioButton
               android:id="@+id/radio1"
               android:layout_width="match_parent"
               android:layout_height="wrap_content"
               android:text="RadioButton" />
<RadioButton
               android:id="@+id/radio2"
               android:layout_width="match_parent"
               android:layout_height="wrap_content"
               android:text="RadioButton" />
</RadioGroup>
<Button
               android:id="@+id/button1"
               android:layout_width="match_parent"
               android:layout_height="wrap_content"
               android:text="@string/str_next" />
</LinearLayout>
</RelativeLayout>

Step 6: The activity

Now the next thing I have on my mind is the activity. I need to fetch the questions from database and display one by one. When the activity starts three things are done:
  1. Data is fetched from database in a list
  2. First question is displayed on the view
  3. A score is initialized to zero
All of this is written in the onCreate() of the activity as seen below:

package com.example.triviality;
import java.util.List;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.TextView;
public class QuizActivity extends Activity {
List<Question> quesList;
int score=0;
int qid=0;
Question currentQ;
TextView txtQuestion;
RadioButton rda, rdb, rdc;
Button butNext;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz);
DbHelper db=new DbHelper(this);
quesList=db.getAllQuestions();
currentQ=quesList.get(qid);
txtQuestion=(TextView)findViewById(R.id.textView1);
rda=(RadioButton)findViewById(R.id.radio0);
rdb=(RadioButton)findViewById(R.id.radio1);
rdc=(RadioButton)findViewById(R.id.radio2);
butNext=(Button)findViewById(R.id.button1);
setQuestionView();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_quiz, menu);
return true;
}
private void setQuestionView()
{
txtQuestion.setText(currentQ.getQUESTION());
rda.setText(currentQ.getOPTA());
rdb.setText(currentQ.getOPTB());
rdc.setText(currentQ.getOPTC());
qid++;
}
}

Here is what it looks like:
final look
Next I need to add the event-handler for the “Next” button as follows:

butNext.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
RadioGroup grp=(RadioGroup)findViewById(R.id.radioGroup1);
RadioButton answer=(RadioButton)findViewById(grp.getCheckedRadioButtonId());
if(currentQ.getANSWER().equals(answer.getText()))
{
score++;
}
currentQ=quesList.get(qid);
setQuestionView();
}
});

Step 7: The result activity

Lastly, when the quiz ends we display a new activity containing the final score. So I have created a new activity called ResultActivity. Here is the layout for the activity called activity_result.xml:

<RelativeLayout 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"
   tools:context=".ResultActivity" >
<LinearLayout
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:layout_alignParentBottom="true"
       android:layout_alignParentLeft="true"
       android:layout_alignParentRight="true"
       android:layout_alignParentTop="true"
       android:orientation="vertical" >
<RatingBar
           android:id="@+id/ratingBar1"
           android:layout_width="match_parent"
           android:layout_height="wrap_content"
           android:numStars="5"
           android:stepSize="1"/>
<TextView
           android:id="@+id/textResult"
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:layout_weight="0.08"
           android:text="Large Text"
           android:textAppearance="?android:attr/textAppearanceLarge" />
</LinearLayout>
</RelativeLayout>



 

Now I need a way of transition from the QuizActivity to ResultActivity. And  it is going to come at a click of our “Next” button. So now the click event listener changes and finally quiz activity looks like this.

package com.example.triviality;
import java.util.List;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
public class QuizActivity extends Activity {
List<Question> quesList;
int score=0;
int qid=0;
Question currentQ;
TextView txtQuestion;
RadioButton rda, rdb, rdc;
Button butNext;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz);
DbHelper db=new DbHelper(this);
quesList=db.getAllQuestions();
currentQ=quesList.get(qid);
txtQuestion=(TextView)findViewById(R.id.textView1);
rda=(RadioButton)findViewById(R.id.radio0);
rdb=(RadioButton)findViewById(R.id.radio1);
rdc=(RadioButton)findViewById(R.id.radio2);
butNext=(Button)findViewById(R.id.button1);
setQuestionView();
butNext.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
RadioGroup grp=(RadioGroup)findViewById(R.id.radioGroup1);
RadioButton answer=(RadioButton)findViewById(grp.getCheckedRadioButtonId());
Log.d("yourans", currentQ.getANSWER()+" "+answer.getText());
if(currentQ.getANSWER().equals(answer.getText()))
{
score++;
Log.d("score", "Your score"+score);
}
if(qid<5){
currentQ=quesList.get(qid);
setQuestionView();
}else{
Intent intent = new Intent(QuizActivity.this, ResultActivity.class);
Bundle b = new Bundle();
b.putInt("score", score); //Your score
intent.putExtras(b); //Put your score to your next Intent
startActivity(intent);
finish();
}
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_quiz, menu);
return true;
}
private void setQuestionView()
{
txtQuestion.setText(currentQ.getQUESTION());
rda.setText(currentQ.getOPTA());
rdb.setText(currentQ.getOPTB());
rdc.setText(currentQ.getOPTC());
qid++;
}
}

Now last thing is to put in code to display results as stars in the RatingBar. The code goes like this:

package com.example.triviality;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.RatingBar;
import android.widget.TextView;
public class ResultActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_result);
//get rating bar object
RatingBar bar=(RatingBar)findViewById(R.id.ratingBar1);
//get text view
TextView t=(TextView)findViewById(R.id.textResult);
//get score
Bundle b = getIntent().getExtras();
int score= b.getInt("score");
//display score
bar.setRating(score);
switch (score)
{
case 1:
case 2: t.setText("Oopsie! Better Luck Next Time!");
break;
case 3:
case 4:t.setText("Hmmmm.. Someone's been reading a lot of trivia");
break;
case 5:t.setText("Who are you? A trivia wizard???");
break;
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_result, menu);
return true;
}
}



 

Take a look at my handy work!!


The complete project is attached with the post.
Attachment Size
Triviality.zip 948.76 KB

0 comments:

Post a Comment

Followers