'Spinner wont show selected and wont respond to item selection

I'm trying to make a very very simple spinner at least, as follows:

XML:

<Spinner
     android:id="@+id/spinner_categories"
     android:layout_width="0sp"
     android:layout_height="wrap_content"
     android:drawSelectorOnTop="true"
     android:layout_weight="1"
     android:textColor="#000000"
     android:spinnerMode="dropdown"/>

JAVA:

spinnerCategories = findViewById(R.id.spinner_categories);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
                getApplicationContext(),
                android.R.layout.simple_spinner_item,
                categories);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerCategories.setAdapter(adapter);
Log.d(Utilities.LOG_FLAG, "SPINNER: " + spinnerCategories.toString());
spinnerCategories.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int position, long l) {
                Toast.makeText(context, categories.get(position).toString(), Toast.LENGTH_SHORT).show();
                Log.d(Utilities.LOG_FLAG, "SELECTED");
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {
                Log.d(Utilities.LOG_FLAG, " NOT SELECTED");
            }
        });

I can see the entire list, but once I click on an item, nothing happans, and it wont show the selection at all, even if I use setSelection(), and if I try to do spinnerCategories.getSelectedItem().toString() I get a NullPointerException. I tried searching the web a lot, but none solution seems to help me...


Edit

For some reason when I load the page and then I go out of the page and reenter it, only then it will show the selected items of the spinner

  • On the first load it shows for a very brief second and then it's gone until the page is reentered the second time


Solution 1:[1]

The setOnItemSelectedListener gets triggered when you click on an element from the drop down menu .. to fetch the selected item you need to use .getSelectedItemPosition() something like categoriesList.get(spinner.getSelectedItemPosition)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Narendra_Nath