dsb
dsb

Reputation: 2527

updating spinner based on another spinner's selected item

What is wrong with this code?

I'm having two spinners. One for 'category' and the second for 'subcategory'. When an item is chosen in the category spinner I want to re-load the relevant sub-categories accordingly.

        mSpnrCategory.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                // SubCategories
                String[] aSubCategory = new String[SUBCATS.length];

... Some code for preparing aSubCategory.

                ArrayAdapter<String> dataAdapterSubCategories = new ArrayAdapter<String>(NewRequestActivity.this, android.R.layout.simple_spinner_item, aSubCategory);
                dataAdapterSubCategories.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                mSpnrSubCategory.setAdapter(dataAdapterSubCategories);
            }

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

            }
        });

when the activity is loaded this code is called and it works fine loading the subcategories of the first category. However, when I change category manually this code is called but results with empty spinner for subcategories. I can't figure out why. Any ideas?

Upvotes: 3

Views: 1516

Answers (1)

Linh
Linh

Reputation: 61039

Define your subcategory adapter (mSpnrSubCategory) as a global variable.
Then whenever category spinner click, change the data of subcategory then notifyDataSetChanged();

    ArrayAdapter<String> mSpnrSubCategory;
    ArrayList<String> aSubCategory;
    mSpnrCategory.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
         @Override
         public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
               // SubCategories
               ...
               mSpnrSubCategory.notifyDataSetChanged();    
         }
    });

I suggest to use ArrayList<String> instead of String[]
Hope this help

Upvotes: 2

Related Questions