In the Android application there is a SQL database.

The task is to get a random record using the Random class.

Algorithm:

  1. Make the necessary request to the database
  2. We get the number of records after the request
  3. We generate a random number
  4. Moving to a random entry
  5. Take her

    if(countQuestion!=0){ Cursor cursor = db.query(EgeDBHelper.QUESTIONS_TABLE, new String[]{EgeDBHelper.COLUMN_ID, EgeDBHelper.LESSON_ID, EgeDBHelper.QUESTION_TYPE, EgeDBHelper.QUESTION}, EgeDBHelper.LESSON_ID+"='"+id.toString()+"' AND "+EgeDBHelper.QUESTION_TYPE+"='"+(i+1)+"'", null, null, null, null);//Запрос for(int j = 0; j < countQuestion; j++){ int a = random.nextInt(cursor.getCount()); cursor.move(a); Log.d("Random", String.valueOf(a)+" "+String.valueOf(cursor.getCount())); int questionID = cursor.getInt(cursor.getColumnIndex(EgeDBHelper.COLUMN_ID)); questions.add(new Question(questionID, db)); } cursor.close(); } } 

The compiler produces:

 android.database.CursorIndexOutOfBoundsException: Index 42 requested, with a size of 42 

Logs:

 D/Random: 30 42 D/Random: 27 42 D/AndroidRuntime: Shutting down VM 

    1 answer 1

    You use the wrong method to set the cursor to a position.

    The move method moves the cursor to the number of positions passed from the current position, as an argument, and does not set to the specified position.

    You need a moveToPosition method

    • Thank you very much, did not know - Eugene Manko
    • Please) I did not know myself until I looked into the docks) - YuriySPb