jeudi 14 mai 2015

Pass string variable to db helper and use in query

I have created two string variables, 'questionString' and 'answerSetId' - the first of which I have assigned to a textview - the second of which I would like to pass to my db helper class:

    public void showNextRandomQuestion3() {

        SQLDatabaseHelper db = new SQLDatabaseHelper(this);

        //get the data from the database
        List<List<String>> listList = db.getAllAnswersByQuestion1();

        //Get the question/text/answer Strings
        List<String> questionStrings = listList.get(0); //question Strings
        List<String> answerSetIds = listList.get(4);

        //Generate random index
        Random r = new Random();
        int rand = Math.abs((r.nextInt() % questionStrings.size()));

        //get answer description for randomly selected question
        String questionString = questionStrings.get(rand);  
        String answerSetId = answerSetIds.get(rand); 

        questionView.setText(questionString);

        }

In my db helper class, I want to use this string variable as pat of my query:

public List<List<String>> getAnswers() {

    List<String> array1 = new ArrayList<String>();    
    List<String> array2 = new ArrayList<String>();  

    SQLiteDatabase db = this.getReadableDatabase();

    String selectQuery = "SELECT  * FROM " + TABLE_ANSWERS + "WHERE " + ASID
            + " = " + ??answerSetId??;

   Cursor c = db.rawQuery(selectQuery, null);
   if (c.moveToFirst()) {
    do {

     String textdescr = c.getString(c.getColumnIndex(TDESCR));
     String answersdescr = c.getString(c.getColumnIndex(ADESCR));
     array1.add(textdescr);
     array2.add(answersdescr);;

    } while (c.moveToNext());

 }
   List< List<String> > listArray2 = new ArrayList< List<String> >();
   listArray2.add(array1);
   listArray2.add(array2);

   return listArray2;
}

What would be the best way to achieve this?

Aucun commentaire:

Enregistrer un commentaire