In the Android application there is a SQL database.
The task is to get a random record using the Random class.
Algorithm:
- Make the necessary request to the database
- We get the number of records after the request
- We generate a random number
- Moving to a random entry
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