I know that in Android the SQL Order BY RANDOM() LIMIT 2 will output two random strings, but it puts both strings into the same TextView. I’d like to get two random strings and put them in two separate TextViews. This code gets two random strings and outputs them into the same textview:
//--- DBAdapter method
public String getRandomHP1() {
Cursor cursor = this.db.query(
"hdtable Order BY RANDOM() LIMIT 2",
new String[] { KEY_HP }, null, null, null, null, null);
String result = "";
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
result = result + cursor.getString(0);
}
return result;
}
//--- Main Activity
String r1 = dba.getRandomHP1();
dba.close();
optionB_TV.setText(r1);
So then I tried the below code to try and separate the two random strings into two string arrays, but it crashed the app. Can someone let me know what I’m doing wrong? Thanks!
//--- DBAdapter method
public String[] getRandomHP2() {
Cursor cursor = this.db.query(
"hdtable Order BY RANDOM() LIMIT 2",
new String[] { KEY_HP }, null, null, null, null, null);
if (cursor != null) {
for (cursor.moveToFirst(); !cursor.isAfterLast();){
String colStrings[] = new String[2];
colStrings[0] = cursor.getString(0);
colStrings[1] = cursor.getString(1);
return colStrings;
}
}
return null;
}
//---Main Activity
String[] r2 = dba.getRandomHP2();
dba.close();
optionB_TV.setText(r2[0]);
optionC_TV.setText(r2[1]);
Using the code
You are constantly moving to the first value in your cursor.. You will never get the 2nd value.. Additionally, you are trying to retrieve a column that doesn’t exist using
cursor.getString(1)which is likely where your crash is occuringtry this instead
Also.. don’t forget to close your cursor when you are done with it..
Just call
cursor.close();to do so