Poperton
Poperton

Reputation: 2148

How to change a variable from an activity inside my adapter (java class change variable passed to it)

My Activity has the value Sound selectedToe. I want my soundPageChangeListener to be able to update the selectedToe of the activity, so I pass selectedToe like this:

SoundPageChangeListener soundPageChangeListener = new SoundPageChangeListener(soundsToe, selectedToe);

however, when I change selectedToe inside soundPageChangeListener:

public class SoundPageChangeListener implements ViewPager.OnPageChangeListener {

    private ArrayList<Sound> sounds;
    Sound currentSound;

    public SoundPageChangeListener(ArrayList<Sound> sounds, Sound currentSound) {
        this.sounds = sounds;
        this.currentSound = currentSound;
    }

    @Override
    public void onPageSelected(int position) {
        Sound sound = sounds.get(position);
        currentSound = sound;
    }

the selectedToe on the activity still null.

Aren't all java values pointers? If I change something inside the listener, shouldn't it change outside?

Upvotes: 1

Views: 48

Answers (1)

sonique
sonique

Reputation: 4772

You can make SoundPageChangeListener inner class of your activity, so the Listener can access to the Activity selectedToe variable. Having an inner class will allow this class SoundPageChangeListener to have visibility and access to your activity selectedToe variable.

The pointer is not kept in your scenario as you are creating a new class instance. Your are assigning currentSound not re-pointing to the memory address.

Then in onPageSelected assign selectedToe with sound


class YourActivity {
    ...
    Sound selectedToe = currentSound // set the default sound if any

    // Inside the activity, declare your listener
    public class SoundPageChangeListener implements ViewPager.OnPageChangeListener {

        private ArrayList<Sound> sounds;

        // only the sound list is required here
        public SoundPageChangeListener(ArrayList<Sound> sounds) {
            this.sounds = sounds;
        }

        @Override
        public void onPageSelected(int position) {
            Sound sound = sounds.get(position);
            YourActivity.this.selectedToe = sound
        }
    }
}

Upvotes: 1

Related Questions