-7

Here is my main activity, I don't know where should I put the code for the question to generate random question for my application quiz. The concept is to generate random question for the user.

qid is the string that holds the questions

      package com.example.triviality;
    import java.util.List;
    import java.util.Random;

    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<8){
                        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++;
        }
    }

I dont know where to put the code to random the qid

heres the code for my Database that contains the questions for the quiz

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("The total number of items representable by a 4 byte binary word (using conventionalabbreviations) is?","16G", "32M", "4G", "4G");
        this.addQuestion(q1);
        Question q2=new Question("Using two's complement encoding, subtract 11100 from 01101, and report the result as a5-bit two's complement binary number.", "101001", "01001", "10001", "10001");
        this.addQuestion(q2);
        Question q3=new Question("Convert the 8-bit two's complement number 10001111 into decimal.","-241", "-143","-113", "-113" );
        this.addQuestion(q3);
        Question q4=new Question("what do you know about JP?", "JP is programmer home", "JP also realigy home", "all answer is true","all answer is true");
        this.addQuestion(q4);
        Question q5=new Question("what do you learn in JP?","Realigy","Programming","all answer is true","all answer is true");
        this.addQuestion(q5);
        Question q6=new Question("Assembly Language instruction sets can be categorized into three basic types ofinstruction:","Direct, Register, and Indirect","High Level, Assembly, and Machine","Operations, Data Movement and Control","Operations, Data Movement and Control");
        this.addQuestion(q6);
        Question q7=new Question("A label in assembly language code is:","Realigy","Programming","all answer is true","all answer is true");
        this.addQuestion(q7);
        Question q8=new Question("what do you learn in JP?","An abbreviation for an instruction","PAn adhesive sticker placed on the front page of the code","A symbolic representation of a memory location","A symbolic representation of a memory location");
        this.addQuestion(q8);
        Question q9=new Question("what do you learn in JP?","Realigy","Programming","all answer is true","all answer is true");
        this.addQuestion(q9);
        Question q10=new Question("what do you learn in JP?","Realigy","Programming","all answer is true","all answer is true");
        this.addQuestion(q10);
        Question q11=new Question("what do you learn in JP?","Realigy","Programming","all answer is true","all answer is true");
        this.addQuestion(q11);
        Question q12=new Question("what do you learn in JP?","Realigy","Programming","all answer is true","all answer is true");
        this.addQuestion(q12);
        Question q13=new Question("what do you learn in JP?","Realigy","Programming","all answer is true","all answer is true");
        this.addQuestion(q13);
        Question q14=new Question("what do you learn in JP?","Realigy","Programming","all answer is true","all answer is true");
        this.addQuestion(q14);
        Question q15=new Question("what do you learn in JP?","Realigy","Programming","all answer is true","all answer is true");
        this.addQuestion(q15);
    }
    @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;
    }
}
  • 5
    Please, describe in detail what you want to do and what your problem is exactly. You write about code you don't know where to put. Do you have that code? It's realy exhausting reading all your code in order to understand your problem in detail. So, please help us. Reading [How to create a Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve) would be appreciated. – Peter Mar 09 '16 at 12:37
  • My problem is i dont know where I should put the code in order for my QID to go random numbers. – Deleted User Mar 09 '16 at 12:51
  • What is the code doing you talk about? Do you know how to generate random numbers? Do you want to randomize you `qid` var? Is that what you are trying to do? If so, read the answer of [generating-unique-random-numbers-in-java](http://stackoverflow.com/questions/8115722/generating-unique-random-numbers-in-java) – Peter Mar 09 '16 at 12:58
  • yes I want to randomize my qid the code is about quiz application – Deleted User Mar 09 '16 at 13:05

2 Answers2

0
"SELECT * FROM" + TABLE_QUEST + "ORDER BY RANDOM()";
0

What I have understand so far:

You want to make pick a random question from your quesList and don't know how to do it - right? Ok..

Java solution:

You have to introduce a java.util.Random member variable, because it is not a good idea to instantiate a new Random instance every time you want to get a random number.

In your code

currentQ=quesList.get(qid);

you pick the qidth question from that list, but you want to pick a random question.

Use java.util.Random#nextInt(int n) where the random number will be picked from [0,n) - means n is not part of the set. So questList.size() is a hot candidate for n.

After that, it is a good idea to remove the picked question from the questList, because you don't want to pick a question twice, do you?

Database solution:

A more efficient solution is to select 8 questions ordered randomly from your database.

If you use a SqlLite database the query will look at @rva answer. Adding a limit expression would make this solution perform even better.

However, you did not tell us anything about your database. That is way I cannot say more about a database solution.

Peter
  • 4,752
  • 2
  • 20
  • 32