426
votes

I am working on an android project and I am using a spinner which uses an array adapter which is populated from the database.

I can't find out how I can set the selected item programmatically from the list. For example if, in the spinner I have the following items:

  • Category 1
  • Category 2
  • Category 3

How would I programmatically make Category 2 the selected item when the screen is created. I was thinking it might be similar to c# I.E Spinner.SelectedText = "Category 2" but there doesn't seem to be any method similar to this for Android.

22
Please follow this link : [How to set selection on spinner item][1] [1]: stackoverflow.com/questions/16358563/…Maddy
You can pass your index into spinner.setSelection(). That would work just fine. You can also create a method that can help you match your indexes to their actual strings.Taslim Oseni

22 Answers

830
votes

Use the following: spinnerObject.setSelection(INDEX_OF_CATEGORY2).

90
votes

No one of these answers gave me the solution, only worked with this:

mySpinner.post(new Runnable() {
    @Override
    public void run() {
        mySpinner.setSelection(position);
    }
});
42
votes
public static void selectSpinnerItemByValue(Spinner spnr, long value) {
    SimpleCursorAdapter adapter = (SimpleCursorAdapter) spnr.getAdapter();
    for (int position = 0; position < adapter.getCount(); position++) {
        if(adapter.getItemId(position) == value) {
            spnr.setSelection(position);
            return;
        }
    }
}

You can use the above like:

selectSpinnerItemByValue(spinnerObject, desiredValue);

& of course you can also select by index directly like

spinnerObject.setSelection(index);
32
votes

Some explanation (at least for Fragments - never tried with pure Activity). Hope it helps someone to understand Android better.

Most popular answer by Arun George is correct but don't work in some cases.
The answer by Marco HC uses Runnable wich is a last resort due to additional CPU load.

The answer is - you should simply choose correct place to call to setSelection(), for example it works for me:

@Override
public void onResume() {
    super.onResume();

    yourSpinner.setSelection(pos);
 }

But it won't work in onCreateView(). I suspect that is the reason for the interest to this topic.

The secret is that with Android you can't do anything you want in any method - oops:( - components may just not be ready. As another example - you can't scroll ScrollView neither in onCreateView() nor in onResume() (see the answer here)

17
votes

To find a value and select it:

private void selectValue(Spinner spinner, Object value) {
    for (int i = 0; i < spinner.getCount(); i++) {
        if (spinner.getItemAtPosition(i).equals(value)) {
            spinner.setSelection(i);
            break;
        }
    }
}
15
votes

Why don't you use your values from the DB and store them on an ArrayList and then just use:

yourSpinner.setSelection(yourArrayList.indexOf("Category 1"));
10
votes

The optimal solution is:

    public String[] items= new String[]{"item1","item2","item3"};
    // here you can use array or list 
    ArrayAdapter adapter= new ArrayAdapter(Your_Context, R.layout.support_simple_spinner_dropdown_item, items);
    final Spinner itemsSpinner= (Spinner) findViewById(R.id.itemSpinner);
itemsSpinner.setAdapter(adapter);

To get the position of the item automatically add the following statement

itemsSpinner.setSelection(itemsSpinner.getPosition("item2"));
7
votes

You can make a generic method for this kind of work as I do in my UtilityClass which is

public void SetSpinnerSelection(Spinner spinner,String[] array,String text) {
    for(int i=0;i<array.length;i++) {
        if(array[i].equals(text)) {
            spinner.setSelection(i);
        }
    }
}
6
votes

You can easily set like this: spinner.setSelection(1), instead of 1, you can set any position of list you would like to show.

5
votes

I have a SimpleCursorAdapter so I have to duplicate the data for use the respose in this post. So, I recommend you try this way:

for (int i = 0; i < spinnerRegion.getAdapter().getCount(); i++) {
    if (spinnerRegion.getItemIdAtPosition(i) == Integer
        .valueOf(signal.getInt(signal
            .getColumnIndexOrThrow("id_region")))) {
        spinnerRegion.setSelection(i);
        break;
    }
}

I think that is a real way

3
votes

I know that is already answered, but simple code to select one item, very simple:

spGenre.setSelection( ( (ArrayAdapter) spGenre.getAdapter()).getPosition(client.getGenre()) );
2
votes

If you have a list of contacts the you can go for this:

((Spinner) view.findViewById(R.id.mobile)).setSelection(spinnerContactPersonDesignationAdapter.getPosition(schoolContact.get(i).getCONT_DESIGNATION()));
2
votes
  for (int x = 0; x < spRaca.getAdapter().getCount(); x++) {
            if (spRaca.getItemIdAtPosition(x) == reprodutor.getId()) {
                spRaca.setSelection(x);
                break;
            }
        }
2
votes

This is work for me.

 spinner.setSelection(spinner_adapter.getPosition(selected_value)+1);
2
votes

This is stated in comments elsewhere on this page but thought it useful to pull it out into an answer:

When using an adapter, I've found that the spinnerObject.setSelection(INDEX_OF_CATEGORY2) needs to occur after the setAdapter call; otherwise, the first item is always the initial selection.

// spinner setup...
spinnerObject.setAdapter(myAdapter);
spinnerObject.setSelection(INDEX_OF_CATEGORY2);

This is confirmed by reviewing the AbsSpinner code for setAdapter.

2
votes

This is what I use in Kotlin:

spinner.setSelection(resources.getStringArray(R.array.choices).indexOf("Choice 1"))
1
votes

Here is the Kotlin extension I am using:

fun Spinner.setItem(list: Array<CharSequence>, value: String) {
    val index = list.indexOf(value)
    this.post { this.setSelection(index) }
}

Usage:

spinnerPressure.setItem(resources.getTextArray(R.array.array_pressure), pressureUnit)
0
votes

In my case, this code saved my day:

public static void selectSpinnerItemByValue(Spinner spnr, long value) {
    SpinnerAdapter adapter = spnr.getAdapter();
    for (int position = 0; position < adapter.getCount(); position++) {
        if(adapter.getItemId(position) == value) {
            spnr.setSelection(position);
            return;
        }
    }
}
0
votes

Most of the time spinner.setSelection(i); //i is 0 to (size-1) of adapter's size doesn't work. If you just call spinner.setSelection(i);

It depends on your logic.

If view is fully loaded and you want to call it from interface I suggest you to call

spinner.setAdapter(spinner_no_of_hospitals.getAdapter());
spinner.setSelection(i); // i is 0 or within adapter size

Or if you want to change between activity/fragment lifecycle, call like this

spinner.post(new Runnable() {
  @Override public void run() {
    spinner.setSelection(i);
  }
});
0
votes

I had made some extension function of Spinner for loading data and tracking item selection.

Spinner.kt

fun <T> Spinner.load(context: Context, items: List<T>, item: T? = null) {
    adapter = ArrayAdapter(context, android.R.layout.simple_spinner_item, items).apply {
        setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
    }

    if (item != null && items.isNotEmpty()) setSelection(items.indexOf(item))
}

inline fun Spinner.onItemSelected(
    crossinline itemSelected: (
        parent: AdapterView<*>,
        view: View,
        position: Int,
        id: Long
    ) -> Unit
) {
    onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
        override fun onNothingSelected(parent: AdapterView<*>?) {
        }

        override fun onItemSelected(parent: AdapterView<*>, view: View, position: Int, id: Long) {
            itemSelected.invoke(parent, view, position, id)
        }
    }
}

Usaage Example

val list = listOf("String 1", "String 2", "String 3")
val defaultData = "String 2"

// load data to spinner
your_spinner.load(context, list, defaultData)

// load data without default selection, it points to first item
your_spinner.load(context, list)

// for watching item selection
your_spinner.onItemSelected { parent, view, position, id -> 
    // do on item selection
}
-1
votes

This worked for me:

@Override
protected void onStart() {
    super.onStart();
    mySpinner.setSelection(position);
}

It's similar to @sberezin's solution but calling setSelection() in onStart().

-1
votes

I had the same issue since yesterday.Unfortunately the first item in the array list is shown by default in spinner widget.A turnaround would be to find the previous selected item with each element in the array list and swap its position with the first element.Here is the code.

OnResume()
{
int before_index = ShowLastSelectedElement();
if (isFound){
      Collections.swap(yourArrayList,before_index,0);
   }
adapter = new ArrayAdapter<String>(CurrentActivity.this,
                            android.R.layout.simple_spinner_item, yourArrayList);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item;                    yourListView.setAdapter(adapter);
}
...
private int ShowLastSelectedElement() {
        String strName = "";
        int swap_index = 0;
        for (int i=0;i<societies.size();i++){
            strName = yourArrayList.get(i);
            if (strName.trim().toLowerCase().equals(lastselectedelement.trim().toLowerCase())){
                swap_index = i;
                isFound = true;
            }
        }
        return swap_index;
    }