我知道在 Android 中 SQLOrder BY RANDOM() LIMIT 2
会输出两个随机字符串,但它会将两个字符串放入同一个 TextView 中。我想得到两个随机字符串并将它们放在两个单独的 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);
所以我尝试了下面的代码来尝试将两个随机字符串分成两个字符串数组,但它使应用程序崩溃。有人可以让我知道我做错了什么吗?谢谢!
//--- 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]);