Lucrea Lucrea - 1 month ago 6
Android Question

Index issue on arraylist (Android Studio)

I am trying to create a simple game of guessing the song's title using media player which content from array song based on arraylist numbers in android studio. So I declare an index in the beginning, which is increasing by 1 for each random and it also happens whenever a user click an answer (using method onClick).

ImageButton play, answer1, answer2, answer3;
int[] song = new int[] {R.raw.beautifulithurts, R.raw.iwontletyouwalkaway, R.raw.lebihindah, R.raw.ruletheworld, R.raw.sweetescape, R.raw.thatgirl, R.raw.thisislivingnow, R.raw.thislife, R.raw.thousandmiles, R.raw.u};
int[] image = new int[] {R.drawable.lvlaa, R.drawable.lvlab, R.drawable.lvlac, R.drawable.lvlad, R.drawable.lvlae, R.drawable.lvlaf, R.drawable.lvlag, R.drawable.lvlah, R.drawable.lvlai, R.drawable.lvlaj};
ArrayList<Integer> numbers = new ArrayList<>();
ArrayList<Integer> cloning = new ArrayList<>();
int index = 0, a = 0, b = 1, c = 2, random = 0, x = 0, y = 0, z = 0, benar = 0, salah = 0;
MediaPlayer mp;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.game);

play = (ImageButton) findViewById(R.id.play);
answer1 = (ImageButton) findViewById(R.id.answer1);
answer2 = (ImageButton) findViewById(R.id.answer2);
answer3 = (ImageButton) findViewById(R.id.answer3);

for (int i = 0; i <= song.length; i++) {
numbers.add(i);
}
Collections.shuffle(numbers);

random();

play.setOnClickListener(this);
answer1.setOnClickListener(this);
answer2.setOnClickListener(this);
answer3.setOnClickListener(this);
}

public void prepareAnswer() {...}

public void random() {
mp = MediaPlayer.create(this, song[numbers.get(index)]);
mp.start();
prepareAnswer();
answer1.setImageResource(image[x]);
answer2.setImageResource(image[y]);
answer3.setImageResource(image[z]);
index++;
}

@Override
public void onClick(View v) {...}
}


But every time I relaunch the game, the logcat show an error: array index out of bound exception (size: 10 index:10). How to handle this error and reset the index to 0, for every time I relaunch the game?

Answer

use below code instead of your .....

for (int i = 0; i < song.length; i++) {
            numbers.add(i);
        }

Note:- Problem is you are adding here extra number and accessing that extra value from array list of song which is not present .....eg:-

song have 10 values and you are trying to access 11th value .....