424

How to get spinner selected item's text?

I have to get the text on the item selected in my spinner when i click on the save button. i need the text not the Index.

Psypher
  • 10,717
  • 12
  • 59
  • 83
Harinder
  • 11,776
  • 16
  • 70
  • 126

13 Answers13

875
Spinner spinner = (Spinner)findViewById(R.id.spinner);
String text = spinner.getSelectedItem().toString();
kentsurrey
  • 450
  • 1
  • 5
  • 11
Farhan
  • 13,290
  • 2
  • 33
  • 59
  • have posted my question here http://stackoverflow.com/questions/5818850/android-spinner-selected-item – Harsha M V Apr 29 '11 at 15:46
  • I used the code and the result is not what I need on the debuging mode I found the it gives me a value like {supliers=VITA}. but I only need the value "VITA" any ideas? – Pedro Teran Mar 01 '12 at 21:07
  • I tried this, but I did not get the actual text. I got a string representing a cursor object: `android.database.sqlite.SQLiteCursor@410dfae8`probably because I used a cursor adapter. Any idea what I should do to get the right string? – AdamMc331 Nov 27 '14 at 19:21
  • 1
    yes, the returned value depends on the type of adapter. Your adapter must be of cursor base so it will return cursor. try typecasting it to cursor and then retrieve your value from cursor. – Farhan Nov 28 '14 at 18:12
  • Farhan, this does not make your solution valid, sorry. STRING label is needed. I know how to fetch a value from the database based on ID. – Yar Feb 03 '15 at 13:50
  • @Yar yeah, the solution works for only string base adapter. When I wrote that answer, it were meant to handle string only. Now what is your question? – Farhan Feb 03 '15 at 21:35
  • actually, this returns the toString() result of adapter's selected item, not the text displayed on spinner in every case. – Serdar Samancıoğlu Jun 07 '18 at 07:00
41
TextView textView = (TextView)mySpinner.getSelectedView();
String result = textView.getText().toString();
Juan Mellado
  • 14,973
  • 5
  • 47
  • 54
Ace
  • 411
  • 4
  • 2
  • 6
    you should always include explanation on the solution you propose - http://stackoverflow.com/questions/how-to-answer – Michal Mar 17 '12 at 16:28
37

You have to use the index and the Adapter to find out the text you have

See this example of Spinner

public class MyOnItemSelectedListener implements OnItemSelectedListener {

    public void onItemSelected(AdapterView<?> parent,
        View view, int pos, long id) {
      Toast.makeText(parent.getContext()), "The planet is " +
          parent.getItemAtPosition(pos).toString(), Toast.LENGTH_LONG).show();
    }

    public void onNothingSelected(AdapterView parent) {
      // Do nothing.
    }
}
ccheneson
  • 49,072
  • 8
  • 63
  • 68
17

Spinner returns you the integer value for the array. You have to retrieve the string value based of the index.

Spinner MySpinner = (Spinner)findViewById(R.id.spinner);
Integer indexValue = MySpinner.getSelectedItemPosition();
Shaista Naaz
  • 8,281
  • 9
  • 37
  • 50
15

use this

import java.util.ArrayList;   
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

public class dynamic_spinner_main extends Activity {

    private Spinner m_myDynamicSpinner;
    private EditText m_addItemText;
    private ArrayAdapter<CharSequence> m_adapterForSpinner;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_spinner);

        ///////////////////////////////////////////////////////////////
        //grab our UI elements so we can manipulate them (in the case of the Spinner)
        //    or add listeners to them (in the case of the buttons)
        m_myDynamicSpinner = (Spinner)findViewById(R.id.dynamicSpinner);        
        m_addItemText = (EditText)findViewById(R.id.newSpinnerItemText);
        Button addButton = (Button)findViewById(R.id.AddBtn);
        Button clearButton = (Button)findViewById(R.id.ClearBtn);

        ////////////////////////////////////////////////////////////////
        //create an arrayAdapter an assign it to the spinner
        m_adapterForSpinner = new ArrayAdapter(this, android.R.layout.simple_spinner_item);
        m_adapterForSpinner.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);        
        m_myDynamicSpinner.setAdapter(m_adapterForSpinner);
        m_adapterForSpinner.add("gr");        
        m_myDynamicSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
                // your code here
                Intent mIntent=new Intent(dynamic_spinner_main.this,sampleLocalization.class);
                mIntent.putExtra("lang", m_myDynamicSpinner.getItemIdAtPosition(position));
                System.out.println("Spinner value...."+m_myDynamicSpinner.getSelectedItem().toString());
                startActivity(mIntent);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parentView) {
                // your code here
            }

        });
        ////////////////////////////////////////////////////////////////
        //add listener for addButton
        addButton.setOnClickListener(new OnClickListener(){

            @Override
            public void onClick(View v) {               
                addNewSpinnerItem();
            }                   
        });

        ////////////////////////////////////////////////////////////////
        //add listener for addButton
        clearButton.setOnClickListener(new OnClickListener(){

            @Override
            public void onClick(View v) {
                clearSpinnerItems();
            }           
        });  
    }

    private void addNewSpinnerItem() {
        CharSequence textHolder = "" + m_addItemText.getText();
        m_adapterForSpinner.add(textHolder);
    }

    private void clearSpinnerItems() {
        m_adapterForSpinner.clear();
        m_adapterForSpinner.add("dummy item");
    }       
}

main_spinner.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <EditText android:layout_height="wrap_content" 
            android:layout_margin="4px" 
            android:id="@+id/newSpinnerItemText" 
            android:layout_width="fill_parent"></EditText>
    <Button android:layout_height="wrap_content" 
            android:id="@+id/AddBtn" 
            android:layout_margin="4px" 
            android:layout_width="fill_parent" 
            android:text="Add To Spinner"></Button>
    <Button android:layout_height="wrap_content" 
            android:id="@+id/ClearBtn" 
            android:layout_margin="4px" 
            android:layout_width="fill_parent" 
            android:text="Clear Spinner Items"></Button>
    <Spinner android:layout_height="wrap_content" 
            android:id="@+id/dynamicSpinner" 
            android:layout_margin="4px" 
            android:layout_width="fill_parent"></Spinner>
</LinearLayout>
12
spinner_button.setOnItemSelectedListener(new OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?>arg0, View view, int arg2, long arg3) {

            String selected_val=spinner_button.getSelectedItem().toString();

            Toast.makeText(getApplicationContext(), selected_val ,
                    Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onNothingSelected(AdapterView<?> arg0) {
            // TODO Auto-generated method stub

        }
    });

}
Baby Groot
  • 4,637
  • 39
  • 52
  • 71
Irfan Ali
  • 189
  • 1
  • 9
12

After set the spinner adapter this code will help

spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
            Toast.makeText(getApplicationContext(), "This is " +
                    adapterView.getItemAtPosition(i).toString(), Toast.LENGTH_LONG).show();

            try {
                //Your task here
            }catch (Exception e)
            {
                e.printStackTrace();
            }
        }

        @Override
        public void onNothingSelected(AdapterView<?> adapterView) {

        }
    });
Ahsan
  • 347
  • 3
  • 8
11

One line version:

String text = ((Spinner)findViewById(R.id.spinner)).getSelectedItem().toString();

UPDATE: You can remove casting if you use SDK 26 (or newer) to compile your project.

String text = findViewById(R.id.spinner).getSelectedItem().toString();
Miroslav Hrivik
  • 822
  • 13
  • 16
8
TextView textView = (TextView) spinActSubTask.getSelectedView().findViewById(R.id.tvProduct);

String subItem = textView.getText().toString();
fedorqui
  • 275,237
  • 103
  • 548
  • 598
user2294100
  • 81
  • 1
  • 1
6

It also can be achieved in a little safer way using String.valueOf() like so

Spinner sp = (Spinner) findViewById(R.id.sp_id);
String selectedText = String.valueOf(sp.getSelectedItem());

without crashing the app when all hell breaks loose. The reason behind its safeness is having the capability of dealing with null objects as the argument. The documentation says

if the argument is null, then a string equal to "null"; otherwise, the value of obj.toString() is returned.

So, some insurance there in case of having an empty Spinner for example, which the currently selected item has to be converted to String.

Student
  • 805
  • 1
  • 8
  • 11
4

For spinners based on a CursorAdapter:

  • get the selected item id: spinner.getSelectedItemId()
  • fetch the item name from your database, for example:

    public String getCountryName(int pId){
        Cursor cur = mDb.query(TABLE, new String[]{COL_NAME}, COL_ID+"=?", new String[]{pId+""}, null, null, null);
        String ret = null;
        if(cur.moveToFirst()){
            ret = cur.getString(0);
        }
        cur.close();
        return ret;
    }
    
Ullas
  • 11,450
  • 4
  • 33
  • 50
Yar
  • 4,543
  • 2
  • 35
  • 42
2

For those have HashMap based spinner :

((HashMap)((Spinner)findViewById(R.id.YourSpinnerId)).getSelectedItem()).values().toArray()[0].toString();

If you are in a Fragment, an Adaptor or a Class other than main activities , use this:

((HashMap)((Spinner)YourInflatedLayoutOrView.findViewById(R.id.YourSpinnerId)).getSelectedItem()).values().toArray()[0].toString();

It's just for guidance; you should find your view's id before onClick method.

Arash
  • 696
  • 8
  • 24
2
Spinner spinner = (Spinner) findViewById(R.id.yourspinnerid);
String text = spinner.getSelectedItem().toString();
  • This may well solve the problem, but please also provide an explanation. Many new users come to SO and explanation with your code helps them to learn how to adapt the code to solve their problem. – JenB Dec 27 '15 at 12:18