我已经从我的SQLite数据库创建了一个值数组 - 它只包含来自内部连接表的两个不同列的两个值。
在我的SQLDatabaseHelper.java中:
public List<List<String>> getAllAnswersByQuestion1() {
List<String> array1 = new ArrayList<String>();
List<String> array2 = new ArrayList<String>();
SQLiteDatabase db = this.getReadableDatabase();
String selectQuery = "SELECT * FROM " + TABLE_ANSWERS + " ta, "
+ TABLE_QUESTION + " tq, " + TABLE_QUESTANS + " tqa WHERE ta." + ASID
+ " = " + "tqa." + ASID + " AND tq." + QID + " = "
+ "tqa." + QID;
Cursor c = db.rawQuery(selectQuery, null);
if (c.moveToFirst()) {
do {
String questdescr = c.getString(c.getColumnIndex(QDESCR));
String questid = c.getString(c.getColumnIndex(QID));
array1.add(questdescr);
array2.add(questid);
} while (c.moveToNext());
}
List< List<String> > listArray = new ArrayList< List<String> >();
listArray.add(array1);
listArray.add(array2);
return listArray;
}
我想将这些传递给我的主要活动。具体来说,我想将数组拆分为单独的字符串,以便将这些值分配给单独的edittext字段。
这是我目前在主要活动中的尝试:
public void showNextRandomQuestion()
{
SQLDatabaseHelper db = new SQLDatabaseHelper(this);
StringTokenizer tokens = new StringTokenizer(db.getAllAnswersByQuestion1(), ",");
String first = tokens.nextToken();
String second = tokens.nextToken();
questionView.setText(first);
answerText1.setText(second);
}
然而,代码将无法编译,因为它要么将&#39; getAllAnswersByQuestion1()的返回类型更改为字符串&#39; - 或&#39;删除参数以匹配StingTokenizer(String)&#39;
似乎无法解决这个问题。
答案 0 :(得分:0)
for(List l : db.getAllAnswersByQuestion1()){
for(String s : l){
StringTokenizer tokens = new StringTokenizer(s, ",");
String first = tokens.nextToken();
String second = tokens.nextToken();
questionView.setText(first);
answerText1.setText(second);
}
}
此更新将使您的代码至少工作
答案 1 :(得分:0)
看起来你的问题和答案都存储在QDESCR
字段中,逗号分隔。
如果是这种情况,那么下面的代码就可以了。 我假设你想从列表中选择一个随机问题,给定方法名称。
您可以使用Random
生成列表的随机索引。
您可能希望添加逻辑以防止先前选择的问题再次出现。
以下是获得问题/答案的基本代码,以及问题ID:
public void showNextRandomQuestion() {
//get the data from the database
List<List<String>> listList = db.getAllAnswersByQuestion1();
//Get the question/answer Strings and the question IDs
List<String> questionStrings = listList.get(0); //question and answer Strings
List<String> questionIDs = listList.get(1); //question IDs
//Generate random index
Random r = new Random();
int rand = Math.abs((r.nextInt() % questionStrings.size()));
//get question ID for randomly selected question
String questionID = questionIDs.get(rand);
//Separate out the question/answer of randomly selected question
StringTokenizer tokens = new StringTokenizer(questionStrings.get(rand), ",");
String first = tokens.nextToken();
String second = tokens.nextToken();
questionView.setText(first);
answerText1.setText(second);
}
另请注意,最好使用String.split()
,如the documentation中所述。