0

This question has nothing to with debugging or in other words I'm not trying to monitor the value of a certain variable to verify if the code is running correctly. I have 6 buttons that can be enabled depending on a variable which we will call X. Each button has a different threshold of what X needs to be in order to enable that button. For example, button1 is enabled if X is at least 50, button2 if X is at least 165, etc. I can have an asynctask to poll variable X and enable or disable the buttons but is there a better way?

2 Answers 2

1

Add your variable to a class like so:

public class example { private int X; public int getX() { return X; } public void setX(int x) { X = x; // When X is set notify your watchers } } 

Next create an interface like so:

public interface VariableChangeWatcher { public void variableChanged(int value); } 

If you make your class use this interface you can add watchers or listeners to know when the value of X has changed outside the class:

public class example { VariableChangeWatcher watcher; private int X; public int getX() { return X; } public void setX(int x) { X = x; // When X is set notify your watchers if (watcher != null) watcher.variableChanged(x); } } 

Then in any class that uses example you can simply listen in to the interface to know when the value of X has changed:

public class exampleListener implements VariableChangeWatcher { public exampleListener() { example e = new example(); } @Override public void variableChanged(int value) { // Gets alerted when the X value inside our e variable has changed } } 
Sign up to request clarification or add additional context in comments.

3 Comments

is example e = new example(); optional? I don't see why you need to include this part otherwise your example fits my needs
You would need to declare an instance of 'example' inside 'exampleListener' in order for the 'variableChanged' method to be called. If you don't there is nothing to call that 'variableChanged'.
Thanks for the idea I used a variation of the example you gave
0

Use encapsulation. Do not make x a variable. Make it a class, with a value inside it. Put a setter function on it. Then whenever the setter function is called, have it set the value and enable/disable all the proper buttons. This way you can't forget to do it anywhere- the only way to set it is via the setter method.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.