Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Android, how do I take an action whenever a variable changes?

In an Android app (or Java more generally if it's no different), what is the best way of calling a method whenever a variable's value changes?

like image 539
tsvallender Avatar asked Aug 23 '11 06:08

tsvallender


Video Answer


1 Answers

What you really want to do is set up event-driven model to trigger a listener when an event happen (in your case, say a variable value has changed). This is very common not only for Java, but for other programming languages as well especially in the context of UI programming (though it is not necessarily only for that)

Typically this is done by doing the following steps:

  • Decide the interface that the listener should implement in the case of the event is triggered. For your case, you could call it VariableChangeListener and define the interface as:
      public interface VariableChangeListener {         public void onVariableChanged(Object... variableThatHasChanged);     }  

You could put any argument that you think it is important for the listener to handle here. By abstracting into the interface, you have flexibility of implementing the necessary action in the case of variable has changed without tight coupling it with the class where the event is occurring.

  • In the class where the event occurred (again in your case, the class where the variable could change), add a method to register a listener for the event. If you call your interface VariableChangeListener then you will have a method such as
     // while I only provide an example with one listener in this method, in many cases     // you could have a List of Listeners which get triggered in order as the event      // occurres     public void setVariableChangeListener(VariableChangeListener variableChangeListener) {        this.variableChangeListener = variableChangeListener;     }  

By default there is no one listening to the event

  • In the case of event occurred (variable has changed), you will then trigger the listener, the code would look like something like
     if( variableValue != previousValue && this.variableChangeListener != null) {        // call the listener here, note that we don't want to a strong coupling        // between the listener and where the event is occurring. With this pattern        // the code has the flexibility of assigning the listener        this.variableChangeListener.onVariableChanged(variableValue);    }  

Again this is a very common practice in programming to basically reacts to an event or variable change. In Javascript you see this is as part of onclick(), in Android you could check the event driven model for various listener such as OnClickListener set on a Button onclick event. In your case you will just trigger the listener based on different event which is whenever the variable has changed

like image 181
momo Avatar answered Sep 18 '22 23:09

momo