Capan
Capan

Reputation: 756

How to get integer value of a spinner value?

I'm using a spinner which have some numbers . I need the number which selected by the user for some calculation so I need to convert it to an integer value. Can someone help me ?

Upvotes: 2

Views: 7998

Answers (2)

Prem
Prem

Reputation: 4831

use the below code sample.

 int myNum = 0;

    try {
        myNum = Integer.parseInt(Spinner_NAME.get(position).toString());
    } catch(NumberFormatException nfe) {
       System.out.println("Could not parse " + nfe);
    }

How to retrieve the selected text from spinner ?

Step 1 - In OnCreate Method, add this line.

 Spinner_NAME.setOnItemSelectedListener(this);

Step 2 - In Activity class, add this method

 @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position,
                long id) {

                if(parent.getId() == R.id.Spinner_NAME)
                {
// SpinnerValue_ArrayName - Name of the Array of Values used to populate spinner.
                        String sText = SpinnerValue_ArrayName.get(position).toString(); 
                    } 
    }

Upvotes: 2

anitag95
anitag95

Reputation: 309

Spinners work on models. Therefor:

int number = Integer.parseInt(jSpinner1.getModel().getValue().toString());

The try-catch isn't compulsory, but recommended.

Upvotes: 0

Related Questions