1

I am making a quiz section in my Android App. I made a Database, and made it so the program selects random rows (questions) from the table. These random questions are then displayed in the actual quiz after which the user can see which questions he answered right and wrong. The problem is that in the Activity where the correct answers are displayed, the questions are completely different from what was in the quiz. They seem to also be somehow randomized.

This is the extract from the Database class:

// Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_QUESTION = "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 static final String KEY_OPTD = "optd"; //option d

private SQLiteDatabase myDatabase;

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

@Override
public void onCreate(SQLiteDatabase db1) {

    myDatabase=db1;

    // A new table is created if there is none
    String sql = "CREATE TABLE IF NOT EXISTS " + TABLE_QUESTION + " ( "
            + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + KEY_QUESTION
            + " TEXT, " + KEY_ANSWER + " TEXT, "+ KEY_OPTA +" TEXT, "
            + KEY_OPTB +" TEXT, "+ KEY_OPTC +" TEXT, " + KEY_OPTD + " TEXT)";

    db1.execSQL(sql);

    // Adds questions from this method below
    addQuestions1();
}

@Override
public void onUpgrade(SQLiteDatabase db1, int oldV, int newV) {

    // Drop older table if existed
    db1.execSQL("DROP TABLE IF EXISTS " + TABLE_QUESTION);

    // Creates tables again
    onCreate(db1);
}

// Takes 7 random rows from the table and puts into the topic quiz
public Cursor getRandomDataItemFromDb(String TABLE_QUESTION, String limit) {
    SQLiteDatabase db1 = this.getWritableDatabase();
    Cursor cursor = db1.rawQuery("SELECT * FROM " + TABLE_QUESTION + " ORDER BY RANDOM() LIMIT 7", null);
    if (cursor.moveToFirst()) {
        return cursor;
    }
    return cursor;
}

// Sets the limit of how many questions will be in the quiz
public int rowCount()
{
    int row=7; //There will be 7 questions in a quiz
    return row;
}

public List<Question> getAllQuestions() {

    List<Question> quesList = new ArrayList<Question>();

    String selectQuery = "SELECT * FROM " + TABLE_QUESTION + " ORDER BY RANDOM() LIMIT 7";

    myDatabase=this.getReadableDatabase();

    Cursor cursor = myDatabase.rawQuery(selectQuery, null);

    if (cursor.moveToFirst()) {
        do {
            Question quest = new Question();
            quest.setId(cursor.getInt(0));
            quest.setQUESTION(cursor.getString(1));
            quest.setANSWER(cursor.getString(2));
            quest.setOptionA(cursor.getString(3));
            quest.setOptionB(cursor.getString(4));
            quest.setOptionC(cursor.getString(5));
            quest.setOptionD(cursor.getString(6));

            quesList.add(quest);

        } while (cursor.moveToNext());
    }
    // returns question list
    return quesList;
}

This is the Class where the question list is displayed which shows correct answers and the answers made by the user:

public class QuizViewAnswers1 extends AppCompatActivity {

private ListView listofAnswers;

private List<Question> questionsList;
private Question currentQuestion;

ArrayList<HashMap<String, Object>> originalValues = new ArrayList<HashMap<String, Object>>();

HashMap<String, Object> temp = new HashMap<String, Object>();

public static String KEY_QUESTION = "questions";
public static String KEY_CANS = "canswer";
public static String KEY_YANS = "yanswer";

private CustomAdapter adapter;

ArrayList<String> myAnsList = new ArrayList<String>();

Button homeQuiz;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.quiz_show_ans);
    String selectQuery;
    Intent in = getIntent();
    Bundle b = getIntent().getExtras();
    myAnsList=in.getExtras().getStringArrayList("myAnsList");

    listofAnswers=(ListView)findViewById(R.id.listofAnswers);

    //Initialize the database
    final SQLDatabaseT1 sqldb = new SQLDatabaseT1(this);
    questionsList= sqldb.getAllQuestions();


    for (int i = 0; i < 7; i++) {
        currentQuestion = questionsList.get(i);
        temp = new HashMap<String, Object>();
        temp.put(KEY_QUESTION,  currentQuestion.getQUESTION());
        temp.put(KEY_CANS, currentQuestion.getANSWER());
        temp.put(KEY_YANS, myAnsList.get(i));

        // add the row to the ArrayList
        originalValues.add(temp);

    }

    adapter = new CustomAdapter(QuizViewAnswers1.this, R.layout.ans_list, originalValues);
    listofAnswers.setAdapter(adapter);

    homeQuiz = (Button) findViewById(R.id.quizHome);
    homeQuiz.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(QuizViewAnswers1.this, Quiz.class);
            startActivity(intent);
            finish();
        }
    });
}

// define your custom adapter
private class CustomAdapter extends ArrayAdapter<HashMap<String, Object>> {
    LayoutInflater inflater;

    public CustomAdapter(Context context, int textViewResourceId, ArrayList<HashMap<String, Object>> Strings) {
        super(context, textViewResourceId, Strings);
        inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    // class for caching the views in a row
    private class ViewHolder {

        TextView viewQuestions, viewAnswers, yourAnswers;

    }

    ViewHolder viewHolder;

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        if (convertView == null) {

            convertView = inflater.inflate(R.layout.ans_list, null);
            viewHolder = new ViewHolder();

            viewHolder.viewQuestions = (TextView) convertView.findViewById(R.id.question);

            viewHolder.viewAnswers = (TextView) convertView
                    .findViewById(R.id.correctanswer);
            viewHolder.yourAnswers = (TextView) convertView
                    .findViewById(R.id.useranswer);

            // link the cached views to the convertview
            convertView.setTag(viewHolder);

        } else
            viewHolder = (ViewHolder) convertView.getTag();

        viewHolder.viewQuestions.setText(originalValues.get(position).get(KEY_QUESTION)
                .toString());

        viewHolder.viewAnswers.setText("Correct Answer: " + originalValues.get(position).get(KEY_CANS)
                .toString());
        viewHolder.yourAnswers.setText("Your Answer: " + originalValues.get(position)
                .get(KEY_YANS).toString());

        // return the view to be displayed
        return convertView;
    }
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        // Respond to the action bar's Up/Home button
        case android.R.id.home:
            NavUtils.navigateUpFromSameTask(this);
            return true;
    }
    return super.onOptionsItemSelected(item);
}

}

The pictures show an example where the questions are completely different than from the Correct Answers list. The only thing that remains is the answer made by the user. Question Answers list

What should I change in the QuizViewAnswers1 class? Thanks in advance.

1 Answers1

0

Problem is that you are fetching the questions again with sqldb.getAllQuestions() and then they are randomized again.

The way to do it will be to use the same dataset you fetched to ask the questions. Just store it in some common place (singleton class maybe) and access it from both the quiz activity and the results activity.

zon7
  • 529
  • 3
  • 12
  • Hi zon7, thank you for your reply. Is there any way to alter that part of the code instead of making a separate class: – Anton Chekhov Oct 23 '16 at 21:19
  • final SQLDatabaseT1 sqldb = new SQLDatabaseT1(this); questionsList= sqldb.getAllQuestions(); ? – Anton Chekhov Oct 23 '16 at 21:20
  • If you want the questions to be accesible from two activities no. Is either a singleton or use a static variable in one of them to store the questions. what's the problem with adding another class? – zon7 Oct 23 '16 at 22:18