[英]how to set list of data from database to display randomly at a android-based app?
I've trying to display random data from the database example in my database i have total of 20 question. 我试图显示数据库示例中数据库中的随机数据,我总共有20个问题。 i want to display randomly 10 qns every time i access the app.
我想每次访问应用程序时随机显示10个qns。 And for the second time that i access it, it will display the other 10 qns that has not been display before.
第二次我访问它时,它将显示之前未显示的其他10个qns。
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 我一遍又一遍地测试它,意识到奇怪的是,它无法读取_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. 还有更多,但是我认为这是没有用的,因为我尝试只用_id = 19运行,它可以工作,但是一旦我更改为20,它就会崩溃。
Change this line: 更改此行:
for(int i=0;i<=list3.size();i++)
to be: 成为:
for(int i=0;i<list3.size();i++)
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). 您在循环中进行了1次迭代(在最后一次迭代中,当i = list3.size()时,当您执行list3.get(i)时会得到IndexOutOfBoundsException,因为列表索引基于0,因此第二十和最后元素实际上位于索引19)。
请记住,SQLite的_id
不是基于0的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.