I’ve trying to display random data from the database example in my database i have total of 20 question. i want to display randomly 10 qns every time i access the app. And for the second time that i access it, it will display the other 10 qns that has not been display before.
my code:
ArrayList<Integer> randList = new ArrayList<Integer>();
Random randGenerator = new Random();
ArrayList<String> list2 = new ArrayList<String>(db.selectData("MCQ",new String [] {"_id"}, "testId=0", null, null, null, null));
//random 10 n.o
for(int i=0;i<10;i++)
{
int randNum = randGenerator.nextInt(list2.size());
while (randList.contains(randNum))
{
randNum = randGenerator.nextInt(list2.size());
}
randList.add(randNum);
Log.d("rand no:"+i,String.valueOf(randNum));
}
ArrayList<String> idList = new ArrayList<String>();
//get the 10 _id that are chosen
for (int i=0; i<10;i++)
{
idList.add(list2.get(Integer.valueOf(randList.get(i))));
Log.d("id:"+i,String.valueOf((list2.get(Integer.valueOf(randList.get(i))))));
}
ArrayList<String> list3 = new ArrayList<String>(db.selectData("MCQ",new String [] {"Question"}, null, null, null, null, null));
Log.d("size",String.valueOf(list3.size()));
ArrayList<String> qnsList = new ArrayList<String>();
// == set question in arrangement of randList == //
for(int i=0;i<=list3.size();i++)
{
qnsList.add(list3.get(i));
Log.d("_id:"+i,String.valueOf(list3.get(i)));
}
i have tested it again and again and realized that weirdly, it could not read the data at _id=20
this is what i get in my log cat:
E/AndroidRuntime(1284): java.lang.IndexOutOfBoundsException: Invalid index 20, size is 20
E/AndroidRuntime(1284): at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:257)
there are more, but i think it is useless as i have tried running with just _id=19 and it works but once i change to 20 it crashed.
Change this line:
to be:
You were iterating through the loop 1 too many times (on the last iteration, when i = list3.size() you would get an IndexOutOfBoundsException when you do list3.get(i) since list indexes are 0-based so the twentieth and last element is actually at index 19).