我知道在Android中,SQL Order 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]);
答案 0 :(得分:0)
使用代码
for (cursor.moveToFirst(); !cursor.isAfterLast();){
String colStrings[] = new String[2];
colStrings[0] = cursor.getString(0);
colStrings[1] = cursor.getString(1);
return colStrings;
}
您不断移动到光标中的第一个值..您将永远不会获得第二个值。此外,您尝试使用cursor.getString(1)
检索不存在的列,这可能是您的位置崩溃正在发生
试试这个
int i = 0;
String colStrings[] = new String[cursor.getCount()];
while (cursor.moveToNext())
{
colStrings[i] = cursor.getString(0);
i++;
}
return colStrings;
另外..完成后不要忘记关闭光标..
只需致电cursor.close();
即可