I’m creating a simple multiple choice trivia game in Android where the user has three choices. The correct answer choice is pulled directly from the DB, and the two other wrong choices are randomly selected using a method. I put the correct and 2 wrong answers in an array and shuffle the array. The game works fine when in the random selection method I’m only grabbing one column from the row. Now I’d like to grab 3 columns from each random row. So then my problem is how to write the code that is “get two random rows with three columns and put the resulting array into an array that can be shuffled”. Here’s my working code:
DBAdapter:
// ---Grabs 2 RANDOM ---
public String[] getRandomHA() {
Cursor cursor = this.db.query(
"hdtable Order BY RANDOM() LIMIT 2",
new String[] { KEY_HA }, null, null, null, null, null);
if (cursor != null) {
int i = 0;
String colStrings[] = new String[cursor.getCount()];
while (cursor.moveToNext())
{
colStrings[i] = cursor.getString(0);
i++;
//cursor.close();
}
return colStrings;
}
return null;
}
// --- END Grabs 2 RANDOM ---
Main Activity:
// --- Random 2 answers ----
public void getRandom() {
dba.open();
String[] wrong2 = dba.getRandomHA();
dba.close();
}
shuffle an Array:
// --- shuffle array ----
String[] numbArray = { rightAnswer[2], wrong2[0], wrong2[1] };
List<String> aList = new ArrayList<String>();
for (String s : numbArray)
aList.add(s);
Collections.shuffle(aList);
TextView[] tVs = { optionA_TV, optionB_TV, optionC_TV };
for (int i = 0; i < tVs.length; i++) {
tVs[i].setText(aList.get(i));
}
// --- END shuffle array ----
So is this how I’d write the DB Adapter method?
// ---Grabs 2 RANDOM ---
public String[] getRandomHA() {
Cursor cursor = this.db.query(
"hdtable Order BY RANDOM() LIMIT 2",
new String[] { KEY_Y, KEY_MD, KEY_HA }, null, null, null, null, null);
if (cursor != null) {
int i = 0;
String colStrings[] = new String[cursor.getCount()];
while (cursor.moveToNext())
{
colStrings[i] = cursor.getString(0);
colStrings[i] = cursor.getString(1);
colStrings[i] = cursor.getString(2);
i++;
//cursor.close();
}
return colStrings;
}
return null;
}
// --- END Grabs 2 RANDOM ---
and if the above method is correct, then how would I write the main activity methods to reflect the nested arrays?
The first thing that comes to my mind is to use an instance of the java.util.Random class to call one of the
nextXXX()methods to generate a random number. Use that number to select a row from the database to use as your random wrong answer.