sineverba
sineverba

Reputation: 5172

Android: how get ID of an item selected in a spinner?

I have this private method to render a spinner in a fragment:

private void renderSpinner() {

        List<String> spinnerArray =  new ArrayList<String>();

        for (int i = 0; i<mPromotionList.size(); i++) {

            ModelPromotion modelPromotion = (ModelPromotion) mPromotionList.get(i);
            String name_promotion = modelPromotion.getName();
            int id_promotion = modelPromotion.getIdPromotion();
            spinnerArray.add(name_promotion);
        }

        ArrayAdapter<String> adapter = new ArrayAdapter<String>(mBaseApp, android.R.layout.simple_spinner_item, spinnerArray);

        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        mSpinnerPromotion.setAdapter(adapter);

        mSpinnerPromotion.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> parent,
                                       View view, int pos, long id) {
                String name_promotion_selected = parent.getItemAtPosition(pos).toString();
                //TODO REMOVE
                Log.d(LOGTAG, "Il nome della promo selezionata è " + name_promotion_selected);
            }

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

            }
        });

    }

As you can see, I have "ready" the id_promotion (It's the real value that I need)... And I know that I'm not adding (for now) at the List.

How I can get it, inside the onItemSelected?

Thank you very much

Upvotes: 0

Views: 2526

Answers (1)

LordRaydenMK
LordRaydenMK

Reputation: 13321

You can use the position of the selected item and use that to get the ID from the original list.

((ModelPromotion) mPromotionList.get(pos)).getIdPromotion()

Another option is to create a custom ArrayAdapter subclass that will accept ModelPromotion instead of String and override getItemId to return the idPromotion

An example about custom ArrayAdapter on Github.

Upvotes: 2

Related Questions