i_m_mahii i_m_mahii - 1 month ago 4
Android Question

Getting error after reaching to the last element of array in android

After my array reaches the last index, I got an exception saying that the index is out of bounds. What I wanted to do is to go back to the first index. How can I do that?

Here is my work

String[] name = {"A", "B", "C", "D"};
Button buttonNext;
int i = 0;

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

buttonNext = (Button) findViewById(R.id.buttonNext);
buttonNext.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
i++;
nextText(i);
}
});
}

private void nextText(int id) {
Log.i("Name is ", name[id]);
}

Answer

Change code to this.

 String[] name = {"A", "B", "C", "D"};
    Button buttonNext;
    int i = 0;

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

        buttonNext = (Button) findViewById(R.id.buttonNext);
        buttonNext.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if(i < name.length-1)
                   i++;
                else
                   i=0;

                nextText(i);

            }
        });
    }

    private void nextText(int id) {
        Log.i("Name is ", name[id]);
    }

Output should be as following. first time : Name is B Second time : Name is C Third time : Name is D Forth time : Name is A

Comments