Global variable inside Spinner onItemSelected does not work

614 views Asked by At

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 = "";
        }

    });
2

There are 2 answers

0
Medes On BEST ANSWER

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

Ty DrkStr

1
Sherif El Nady On

I don't know why are using int index = spUsers.getSelectedItemPosition(); to get the index when you can use the position integer provided in onItemSelected() method.