1

i am working on android spinner control. i already have populate list of string to show in spinner like

String[] items = new String[]{ "Office", "Home", "College", "Uncle's Home", "CoDebuggers"};
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, items);
        SpinnerName.setAdapter(adapter);

this is working well but i need to add unique id for my list like

  1. Office = 4

  2. Home = 8

  3. College = 9

  4. Uncle's Home = 10

  5. CoDebiggers = 55

    how can i set there value with String list? and how can i get these values by selected item change?

Community
  • 1
  • 1
Faisal
  • 584
  • 3
  • 11
  • 33
  • Possible duplicate of [https://stackoverflow.com/questions/1625249/android-how-to-bind-spinner-to-custom-object-list](https://stackoverflow.com/questions/1625249/android-how-to-bind-spinner-to-custom-object-list) – yashkal Dec 07 '17 at 08:22
  • Use arraylist with two fields id and title – Vidhi Dave Dec 07 '17 at 08:46

2 Answers2

6

You have to create two array, one for the items and second for the item's value.

String[] items = new String[]{ "Office", "Home", "College", "Uncle's Home", "CoDebuggers"};
int[] items_value = new String[]{ 4, 8, 9, 10, 55};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, items);
SpinnerName.setAdapter(adapter);

Get spinner selected item respective value from value array:

int value = items_value[SpinnerName.getSelectedItemPosition()];

Vidhi Dave
  • 5,614
  • 2
  • 33
  • 55
jd_ptl
  • 76
  • 1
1

Create another array, maintain sizes of both arrays same. One is for items and another one is for itemIds. inside OnclickLisener of spinner call itemsId array like below.

String[] itemsId = new String[]{ "4", "8", "9", "10","55"};
String[] items = new String[]{ "Office", "Home", "College", "Uncle's Home", "CoDebuggers"};
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, items);
    SpinnerName.setAdapter(adapter);
SpinnerName.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {

           String id = itemsId.get(i);
        }
        @Override
        public void onNothingSelected(AdapterView<?> adapterView) {

        }
    });
Teja
  • 787
  • 7
  • 21