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
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 } } 3 Comments
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.