Error Quiz Application

Put your problem here if it does not fit any of the other categories.

Error Quiz Application

Postby hell0_android » Thu Mar 08, 2012 3:31 pm

Hi all,
-Now I am doing a quiz english application...I have create a database in sqlite with name "quiz"
-My Project have two classes:
Class 1: contruct some method acccess database
Code: Select all
public class DatabaseHelper extends SQLiteOpenHelper {

   //The android's default system path of your application database
   private static String DB_PATH="/data/data/android.tuanshaker.quiz.com/databases/";
   private static String DB_NAME="quiz";
   private SQLiteDatabase myDataBase;
   private SQLiteDatabase myData;
   private final Context myContext;
   private static String Table_name="Quiz";
   
   public DatabaseHelper(Context context)
   {
      super(context,DB_NAME,null,1);
      this.myContext=context;
   }
   
   //Create a empty database and rewrite it with your database
   public void createDataBase() throws IOException
   {
      boolean dbExist=checkDataBase();
      if(dbExist)
      {
         
      }
      else
      {
         //by calling this method and empty database will be created in the default system path
         //of your application so we are gonna be able to overwrite that database with our database
         this.getReadableDatabase();
         try
         {
            copyDataBase();
         }
         catch(IOException e)
         {
            e.printStackTrace();
         }
      }
         
   }
   
   public boolean checkDataBase()
   {
      File dbFile = new File(DB_PATH + DB_NAME);
      return dbFile.exists();
   }

   //Operation copy database
   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 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 stream
      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.NO_LOCALIZED_COLLATORS );
   }
   
   @Override
   public synchronized void close()
   {
      if(myDataBase!=null)
      {
         myDataBase.close();
      }
      super.close();
   }
   
   
   
   @Override
   public void onCreate(SQLiteDatabase arg0) {
      // TODO Auto-generated method stub

   }

   @Override
   public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
      // TODO Auto-generated method stub

   }

   //Get Book content //lay noi dung cau hoi theo ID
   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 content of quiz
   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;
   }
   
   //get answer by id
   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 answer from answers where quiz_id='"+quizid+"'", null);
      cur.moveToFirst();
      myData.close();
      return cur;
   }
   
   //get answer list
   public Cursor getAnsList()
   {
      String myPath=DB_PATH+DB_NAME;
      myData=SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
      
      Cursor cur;
      cur=myData.rawQuery("select answer from answers", null);
      cur.moveToFirst();
      myData.close();
      return cur;
   }
   
       //get correct answer
   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;
   }
   
   //update a title
   public boolean UpdateFavourite_Individual(long rowid,String fav)
   {
      String myPath=DB_PATH+DB_NAME;
      myData=SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
      
      ContentValues args=new ContentValues();
      args.put("bookmark", fav);
      return myData.update("lyrics", args, "rowid="+rowid, null)>0;
   }
      
}


Class 2 : activity display interface
Code: Select all
public class QuizAppActivity 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: handle exception
           e.printStackTrace();
      }
       
        c3=db.getCorrAns();
        tvScore=(TextView)findViewById(R.id.tvScore);
        c3.moveToFirst();
        for(int i=0;i<=3;i++)
        {           
           corrAns[i]=c3.getString(0);           
           c3.moveToNext();
        }
       
        radioGroup = (RadioGroup) findViewById(R.id.rdbGp1);
       
        //loi o day la cai su kien nay chi bat cho lan dau tien lan sau khi next cau hoi ko bat duoc su kien do nua
        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
         
         @Override
         public void onCheckedChanged(RadioGroup group, int checkedId) {
            // TODO Auto-generated method stub
            for(int i=0;i<=3;i++)
            {
               //questNo++;
               RadioButton btn=(RadioButton)radioGroup.getChildAt(i);
               //String text;
               
               if(btn.isPressed() && btn.isChecked() && questNo<5)
               {
                  if(corrAns[questNo].equals(btn.getText())&& flag==true)
                  {                     
                     score++;                     
                     flag=false;
                     checked=true;
                     
                  }
                  else if(checked==true)
                  {                     
                     score--;
                     flag=true;
                     checked=true;                                       
                  }
                  
               }
               
            }
            tvScore.setText("Score"+Integer.toString(score)+"/10");
            //Toast.makeText(getBaseContext(),Integer.toString(score)+"/10", Toast.LENGTH_LONG).show();
            Log.e("Score:", Integer.toString(score));
            
         }
         
               
      });
       
        quizQuestion=(TextView)findViewById(R.id.TextView01);
        displayQuestion();
       
        //Display the next options and set listener on next button
       
        Button btnNext=(Button)findViewById(R.id.btnNext);
        btnNext.setOnClickListener(new OnClickListener() {
         
         @Override
         public void onClick(View v) {
            // TODO Auto-generated method stub
            flag=true;
            checked=false;
            questNo++;
            if(questNo<10)
            {               
               c1.moveToNext();
               displayQuestion();
            }
         }
      });
       
       
        //saves the selected values in the database on the save button
        Button btnSave=(Button)findViewById(R.id.btnSave);
        btnSave.setOnClickListener(new OnClickListener() {
         
         @Override
         public void onClick(View v) {
            // TODO Auto-generated method stub
            //score+=1;
                        
         }
      } );
       
       
    }
   
    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 button dynamiccally
          radioButton=new RadioButton(this);
          radioButton.setText(c2.getString(0));
          radioButton.setId(i);
          c2.moveToNext();
          radioGroup.addView(radioButton);
       }
    }
}


When i push radio button in the first time,it work fine...But when we click next button to next question,it alse get event push radio button when value of score not change...

This is link my project: http://www.mediafire.com/?65q0k16rq284sil

Can you help me...:|Thank every body :x
hell0_android
Freshman
Freshman
 
Posts: 9
Joined: Wed Sep 14, 2011 4:39 pm

Top

Re: Error Quiz Application

Postby Phyll » Thu Mar 08, 2012 8:36 pm

hell0_android,

I'm not sure you can fix that using radiobuttons and radiogroup as they are. What I see going on is, after the first selection, the second selection is the same radiobutton. However, removing all the views and recreating them has changed the text and turned all of them off, but not unselected the one that was selected. The radiogroup knows it is already selected so it doesn't do anything when you select it. You have to select another one and then come back to that one for it to work. I guess you could try selecting -1 or something and see what happens.

You really can't have all the buttons unselected as they are at the beginning of each question. I don't think that is a valid state for them to be in. I know when I made an app like that, I used an activity with a dialog theme so that I made a new list of buttons for multiple choice questions (in fact a whole new activity for each one). It used strings for filling in the questions and stuff.

Here is how I did that one:

Code: Select all

From the method that drew the types of questions allowed...

        switch (qType) {                     
        case 0://Multiple Choice
           //Setup the radio group layout. Use number of choices in third
           //element of question strings
           n = Integer.parseInt(qQuestion[2].toString());
           i = 1;
           rg = new RadioGroup(this);
           rg.setLayoutParams(new LayoutParams(
                 ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.WRAP_CONTENT,1.0f));
           //Add each answer choice to the group
           int j = n;
            while (j>0) {
             tempField.setName("radio_"+i);
             tempField.setLabel(qQuestion[i+3]);
             fields.add(tempField);
               fields.elementAt(i).obj = new QRadio(this, qQuestion[i+3],(i==1),i);
              rg.addView((View) fields.elementAt(i).obj);
              i++; j--;
                }//while
            //Add the radio group to the overall linear layout
            ll.addView((View) rg);
          break;//multiplechoice


This is the class extended from radiobutton that made the buttons:

Code: Select all
public class QRadio extends RadioButton {

   public QRadio(Context context, String labelText, boolean dsel, int id) {
      super(context);
       this.setTypeface(Typeface.MONOSPACE);
       this.setText(labelText);
       this.setTextColor(Color.WHITE);
       //this.setPadding(15, 5, 5, 5);
       this.setChecked(dsel);
       this.setLayoutParams(new LayoutParams(
             ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.WRAP_CONTENT,1.0f));
       //Usually this is the order in which they were read from the question
       this.setId(id);
       }//constructor
   
}


Just use this when they hit the Next button to tell which one is checked:

Code: Select all
    int id = rg.getCheckedRadioButtonId();


Hope this helps.

Phyll
Phyll
Master Developer
Master Developer
 
Posts: 648
Joined: Fri Oct 14, 2011 11:19 am

Re: Error Quiz Application

Postby hell0_android » Sat Mar 10, 2012 3:32 am

Thank Phyll
hell0_android
Freshman
Freshman
 
Posts: 9
Joined: Wed Sep 14, 2011 4:39 pm

Top

Return to Other Coding-Problems

Who is online

Users browsing this forum: No registered users and 13 guests