Friday, August 13, 2010

Listen to DROID X Q&A


Listen to internet radio with MOTODEV on Blog Talk Radio

Tuesday, August 3, 2010

Tutorial: Developing a Quiz App on Android




Recently, i had to integrate a quiz module in an e-book application.I would be glad to share my code along with the schema. Using SQLite, i have the following table definitions for my schema:


CREATE TABLE Quiz(Correct_Answer TEXT, Quiz_ID INTEGER PRIMARY KEY, Quiz_Text TEXT)


CREATE TABLE Answers(Answer TEXT, Answer_ID INTEGER PRIMARY KEY, Quiz_ID NUMERIC)


CREATE TABLE Android_Metadata("locale" TEXT DEFAULT 'en_US')

NOTE: Once created the database file is to be placed in the assets folder of the project.






In order to design the layout as shown in the picture above here is the code for main.xml:


main.xml


android:layout_width="fill_parent" 
android:layout_height="fill_parent" 
xmlns:android="http://schemas.android.com/apk/res/android">





android:id="@+id/rdbGp1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_y="30dip"
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
>





android:text="Save" android:id="@+id/btnSave" android:layout_width="100dip" android:layout_height="wrap_content" android:layout_x="50dip" android:layout_y="250dip">




android:layout_x="17dip" 
android:layout_y="15dip" 
android:id="@+id/TextView01" 
android:layout_width="wrap_content" 
android:text="Question" 
android:layout_height="wrap_content">









android:layout_x="100dip" 
android:layout_y="320dip" 
android:id="@+id/tvScore" 
android:layout_width="wrap_content" 
android:text="Score" 
android:layout_height="wrap_content">


-











Here's my Database Helper containing all the methods necessary to create and the Quiz database and to query it afterwards:




DatabaseHelper.java
package com.myapps.quiz;


import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;


import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;


public class DataBaseHelper extends SQLiteOpenHelper{


//The Android's default system path of your application database.
private static String DB_PATH = "/data/data/com.myapps.quiz/databases/";
private static String DB_NAME = "quiz";
private static String Table_name="Quiz";


private SQLiteDatabase myDataBase;
private SQLiteDatabase myData;
private final Context myContext;


/**
* Constructor
* Takes and keeps a reference of the passed context in order to access to the application assets and resources.
* @param context
*/
public DataBaseHelper(Context context) {
super(context, DB_NAME, null, 1);
this.myContext = context;
}






/**
* Creates a empty database on the system and rewrites it with your own database.
* */
public void createDataBase() throws IOException{


boolean dbExist = checkDataBase();
if(dbExist){
//do nothing - database already exist
}else{
CopyFiles();
}
}


private void CopyFiles()
{
try
{
InputStream is = myContext.getAssets().open(DB_NAME);
File outfile = new File(DB_PATH,DB_NAME);
outfile.getParentFile().mkdirs();
outfile.createNewFile();


if (is == null)
throw new RuntimeException("stream is null");
else
{
FileOutputStream out = new FileOutputStream(outfile);
// BufferedOutputStream out = new BufferedOutputStream( new FileOutputStream(outfile));
byte buf[] = new byte[128];
do {
int numread = is.read(buf);
if (numread <= 0) break; out.write(buf, 0, numread); } while (true); is.close(); out.close(); } //AssetFileDescriptor af = am.openFd("world_treasure_hunter_deluxe.apk"); } catch (IOException e) { throw new RuntimeException(e); } } /** * Check if the database already exist to avoid re-copying the file each time you open the application. * @return true if it exists, false if it doesn't */ private boolean checkDataBase(){ SQLiteDatabase checkDB = null; try{ String myPath = DB_PATH + DB_NAME; checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY); }catch(SQLiteException e){ } if(checkDB != null){ checkDB.close(); } return checkDB != null ? true : false; } /** * Copies your database from your local assets-folder to the just created empty database in the * system folder, from where it can be accessed and handled. * This is done by transfering bytestream. * */ private void copyDataBase() throws IOException{ //Open your local db as the input stream InputStream myInput = myContext.getAssets().open(DB_NAME); // Path to the just created empty db String outFileName = DB_PATH + DB_NAME; //Open the empty db as the output stream OutputStream myOutput = new FileOutputStream(outFileName); //transfer bytes from the inputfile to the outputfile byte[] buffer = new byte[1024]; int length; while ((length = myInput.read(buffer))>0){
myOutput.write(buffer, 0, length);
}


//Close the streams
myOutput.flush();
myOutput.close();
myInput.close();


}


public void openDataBase() throws SQLException{


//Open the database
String myPath = DB_PATH + DB_NAME;
myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);


}


@Override
public synchronized void close() {


if(myDataBase != null)
myDataBase.close();


super.close();


}


@Override
public void onCreate(SQLiteDatabase db) {


}


@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {


}






/// Get Book content////////
public Cursor getQuiz_Content(int bookId)
{
String myPath = DB_PATH + DB_NAME;
myData = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);


Cursor cur;
cur=myData.rawQuery("select quiz_text from Quiz where quiz_id='"+bookId+"'",null);
cur.moveToFirst();


myData.close();
return cur;
};
//////////////////////////






/// Get Book content////////
public Cursor getQuiz_List()
{
String myPath = DB_PATH + DB_NAME;
myData = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
int i;


Cursor cur;
cur=myData.rawQuery("select quiz_id,quiz_text,correct_answer from quiz",null);
cur.moveToFirst();
i = cur.getCount();
myData.close();
return cur;
};
//////////////////////////




public Cursor getAns(int quizid)
{
String myPath = DB_PATH + DB_NAME;
myData = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);


Cursor cur;
cur = myData.rawQuery("select answers from answer where quiz_id='"+quizid+"'", null);
cur.moveToFirst();
myData.close();
return cur;
}


public Cursor getAnsList()
{
String myPath = DB_PATH + DB_NAME;
myData = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);


Cursor cur;
cur = myData.rawQuery("select answers from answer", null);
cur.moveToFirst();
myData.close();


return cur;
}




public Cursor getCorrAns()
{
String myPath = DB_PATH + DB_NAME;
myData = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);


Cursor cur;
cur = myData.rawQuery("select correct_answer from quiz", null);
cur.moveToFirst();
myData.close();


return cur;
}
//---updates a title---
/* public boolean UpdateFavourite_Individual(long rowid,String fav)
{
String myPath = DB_PATH + DB_NAME;
myData = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);


ContentValues args = new ContentValues();
args.put("bookmark", fav);
return myData.update("lyrics", args,
"rowid=" + rowid, null) > 0;
}*/
//////////////////




}








Here's the Quiz class to add the front-end functionality(like adding radio buttons and scoring functionality):




Quiz.java


package com.myapps.quiz;


import java.io.IOException;


import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;


public class Quiz extends Activity{
    /** Called when the activity is first created. */
private RadioButton radioButton;
private TextView quizQuestion;
private TextView tvScore;



private int rowIndex = 1;
private static int score=0;
private int questNo=0;
private boolean checked=false;
private boolean flag=true;

private RadioGroup radioGroup;


String[] corrAns = new String[5];

final DataBaseHelper db = new DataBaseHelper(this);

Cursor c1;
Cursor c2;
Cursor c3;

int counter=1;
String label;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        String options[] = new String[19];
     
        
        // get reference to radio group in layout
     RadioGroup radiogroup = (RadioGroup) findViewById(R.id.rdbGp1);
    
    
    
    
     // layout params to use when adding each radio button
     LinearLayout.LayoutParams layoutParams = new RadioGroup.LayoutParams(
                RadioGroup.LayoutParams.WRAP_CONTENT,
                RadioGroup.LayoutParams.WRAP_CONTENT);
    
        try {
db.createDataBase();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
        c3 = db.getCorrAns();
        
        tvScore = (TextView) findViewById(R.id.tvScore);
        
        for (int i=0;i<=4;i++)
        {
         corrAns[i]=c3.getString(0);
         c3.moveToNext();
        
        }
        
        radioGroup = (RadioGroup) findViewById(R.id.rdbGp1);
        
        
        
        
        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {

@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
// TODO Auto-generated method stub
for(int i=0; i
                  RadioButton btn = (RadioButton) radioGroup.getChildAt(i);
                  
                   String text;
                   
                  
                   
                 if (btn.isPressed() && btn.isChecked() && questNo < 5)
                  {
                   
                      Log.e("corrAns[questNo]",corrAns[questNo]);
                  
                 if (corrAns[questNo].equals(btn.getText()) && flag==true)
                 {
                 score++;
                 flag=false;
                 checked = true; 
                 }
                 else if(checked==true)
                 {
                 score--;
                 flag=true;
                 checked = false;
                 }
                 
                 
                 
                 
                  }
             }
tvScore.setText("Score: " + Integer.toString(score) + "/5");
Log.e("Score:", Integer.toString(score));
}
});
        
      
        
        quizQuestion = (TextView) findViewById(R.id.TextView01);
        
        
        displayQuestion();
        
        
        
        /*Displays the next options and sets listener on next button*/
        Button btnNext = (Button) findViewById(R.id.btnNext);
        btnNext.setOnClickListener(btnNext_Listener);

        /*Saves the selected values in the database on the save button*/
        Button btnSave = (Button) findViewById(R.id.btnSave);
        btnSave.setOnClickListener(btnSave_Listener);
        
    
        
        
    }
    
    
    /*Called when next button is clicked*/
    private View.OnClickListener btnNext_Listener= new View.OnClickListener() {

@Override
public void onClick(View v) {
flag=true;
checked = false;
questNo++;

if (questNo < 5)
{
c1.moveToNext();
displayQuestion();
}




}


};
    
/*Called when save button is clicked*/
private View.OnClickListener btnSave_Listener= new View.OnClickListener() {

@Override
public void onClick(View v) {


}
};


private void displayQuestion()
{
//Fetching data quiz data and incrementing on each click

c1=db.getQuiz_Content(rowIndex);

c2 =db.getAns(rowIndex++);


quizQuestion.setText(c1.getString(0));


radioGroup.removeAllViews();
for (int i=0;i<=3;i++)
{
//Generating and adding 4 radio buttons dynamically 
radioButton = new RadioButton(this);
radioButton.setText(c2.getString(0));
radioButton.setId(i);
c2.moveToNext();
radioGroup.addView(radioButton);

}

}



}