0

I have:

  • a String array with an unknown length that's populated with unknown items (let's say fish, bird, cat)
  • an ArrayAdapter and a Spinner that displays the items
  • a variable that contains one unknown item from the string array (let's say cat)

I want to set the Spinner to the value from the variable (cat). What's the most elegant solution? I thought about running the string through a loop and comparing the items with the variable (until I hit cat in this example), then use that iteration's # to set the selection of the Spinner, but that seems very convoluted.

Or should I just ditch the Spinner? I looked around and found a solution that uses a button and dialog field: https://stackoverflow.com/a/5790662/1928813

//EDIT: My current code. I want to use "cow" without having to go through the loop, if possible!

        final Spinner bSpinner = (Spinner) findViewById(R.id.spinner1);
    String[] animals = new String[] { "cat", "bird", "cow", "dog" };
    String animal = "cow";
    int spinnerpos;
    final ArrayAdapter<String> animaladapter = new ArrayAdapter<String>(
            this, android.R.layout.simple_spinner_item, animals);
    animaladapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    bSpinner.setAdapter(animaladapter);

    for (Integer j = 0; j < animals.length; j++) {
        if (animals[j].equals(animal)) {
            spinnerpos = j;
            bSpinner.setSelection(spinnerpos);
        } else {
        };
    }
Community
  • 1
  • 1
BunnyEngine'
  • 47
  • 1
  • 5

1 Answers1

0

(Temporarily) convert your String array to a List so you can use indexOf.

int position = Arrays.asList(array).indexOf(randomVariable);
spinner.setSelection(position);

EDIT:

I understand your problem now. If your String array contains all unique values, you can put them in a HashMap for O(1) retrieval:

HashMap<String, Integer> map = new HashMap<String, Integer>();
for (int i = 0; i < animals.length; i++) {
   map.put(animals[i], i);
} 

String randomAnimal = "cow";
Integer position = map.get(randomAnimal);

if (position != null) bSpinner.setSelection(position);
Makario
  • 2,097
  • 21
  • 19