user3204203
user3204203

Reputation: 19

Android how to get next item on array with button click

i want to get the next item on an array on button click.

array is like this :

String[] pickupLinesItems = { "a", "b", "c" };

then i have this for the spinner

public void onItemSelected(org.holoeverywhere.widget.AdapterView<?> parent,
        View view, int position, long id) {

    position = spinner.getSelectedItemPosition();

    SpinnerAdapter adap = spinner.getAdapter();

    if (adap.equals(pickupLinesAdapter)) {
        switch (position) {
        case 0:
            stopPlaying();
            speakMedia = MediaPlayer.create(this, R.raw.a);
            break;
        case 1:
             stopPlaying();
             speakMedia = MediaPlayer.create(this, R.raw.b);
             break;
        case 2:
             stopPlaying();
             speakMedia = MediaPlayer.create(this, R.raw.c);
             break;

        }
    }
}

public void onClick(View v) {
    // TODO Auto-generated method stub
    int index = 0;

    switch (v.getId()) {
    case R.id.next:
        // here i want to go on the next item on array
        break; 
    case R.id.back:
                    // here i wanna go back one item on the array
        break;
    }
}

how would i do this, i've tried everything and cant seem to get it. i tried to do an if statement but nothing.

Upvotes: 0

Views: 3964

Answers (2)

user3311655
user3311655

Reputation: 31

Need a variable to hold the current index of pickupLinesItems declared at the same scope as String[] pickupLinesItems = { "a", "b", "c" };

For example:

int pickupLinesItemIndex = 0;

Then you could do something like this:

public void onClick(View v) {
    // TODO Auto-generated method stub

    switch (v.getId()) {
    case R.id.next:
        if(pickupLinesItemIndex < pickupLinesItems.length)
        {
          String pickupLine = pickupLinesItemIndex[++pickupLinesItemIndex];
        }
        break; 
    case R.id.back:
        if(pickupLinesItemIndex > 0)
        {
          String pickupLine = pickupLinesItemIndex[--pickupLinesItemIndex];
        }
        break;
    }
}

Upvotes: 3

Embattled Swag
Embattled Swag

Reputation: 1469

Assuming my comment is correct, you could do something like:

//in your onClick
case R.id.next:
    int current = spinner.getSelectedItemPosition();
    spinner.setSelection(current++);
    break;

You could do the same thing in back. Also, make sure to check for boundary conditions (if you're on c, make sure you go to a and not attempt to reach out of the array's bounds).

Upvotes: 0

Related Questions