Search code examples
androidglobal-variablesspinneronitemselectedlistener

Global variable inside Spinner onItemSelected does not work


I've been thinking about this a long while but realy can't figure out what the problem is. The first code piece works in one of my activities. selectedUser is globally declarend and I can use it everywhere.

        spUsers.setAdapter(new MyAdapter(this, R.layout.user_sp_row,userArray));
    spUsers.setOnItemSelectedListener(new OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
            int index = spUsers.getSelectedItemPosition();
            selectedUser = userList.get(index).get(Constants.TAG_UNAME);
        }

        @Override
        public void onNothingSelected(AdapterView<?> parentView) {
            selectedUser = "";
        }

    });

This code does not work allthough it looks the same like the other code I wrote. selectedCat is also globally declared. The thing is the value is set in the onItemSelected method but as soon as it leaves the method selectedCat is an empty string.

        spCat.setAdapter(new MyAdapter(this, R.layout.category_sp_row,tempArray));
    spCat.setOnItemSelectedListener(new OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
            int index = spCat.getSelectedItemPosition();
            selectedCat = categoryList.get(index).get(Constants.TAG_UPID);
        }

        @Override
        public void onNothingSelected(AdapterView<?> parentView) {
            selectedCat = "";
        }

    });

Solution

  • I've got this working by indeed doing everything that needs to be done in the setOnItemSelectedListener().

    Ty DrkStr