I'm having trouble with the following code.
I am getting the the index of item and using it. Now I want to remove it's position from the list so that it doesn't get the same position again, but when I call the method below the app crashes, and when I delete the line myList.remove(randomIndex);
it runs good. Is something wrong with this line?
public void showtime() {
Random rand = new Random();
randomIndex = rand.nextInt(myList.size());
randomName = myList.get(randomIndex);
txtView.setText(randomName);
if (randomIndex==1)) {
imgLabel.setImageResource(R.drawable.Label1);
}
if (randomIndex==2)) {
imgLabel.setImageResource(R.drawable.Label2);
}
if (randomIndex==3)) {
imgLabel.setImageResource(R.drawable.Label3);
}
myList.remove(randomIndex);
}
Ensure that:
1- myList is an ArrayList;
2- When this method is called, myList has almost an element
Each of your if statements has a syntax error. They have an extra )
if (randomIndex==1) {
imgLabel.setImageResource(R.drawable.Label1);
}
if (randomIndex==2) {
imgLabel.setImageResource(R.drawable.Label2);
}
if (randomIndex==3) {
imgLabel.setImageResource(R.drawable.Label3);
}
当您从列表中删除项目时,请确保它不应该是它必须是请试试这个....
它应该是
randomIndex = rand.nextInt(myList.size());
You can check that the generated index is within the list bounds and avoid the crash like this
randomIndex = rand.nextInt(myList.size()-1);
if(randomIndex <= myList.size()-1){
myList.remove(randomIndex)
};
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.