Bahar Azartoos Bahar Azartoos - 2 years ago 506
Android Question

A listener for changing variable in android

I have a variable in my class , I want when that variable changed , I do an action in another class .
in fact I want a listener for changing variable in android (my variable may change every minute)

public class Connect {
public static boolean myBoolean;
//some actions do and myBoolean change
}

public class Selection extends Activity implements OnMenuItemClickListener{

//I want a thing like listener here ,when myboolean changed I do an action (myboolean may change every minute)

}

Answer Source

It's not possible directly. However, you can make your field private, add getters and setters, and create a method of adding listeners (this is called the Observer pattern):

interface ConnectionBooleanChangedListener {
    public void OnMyBooleanChanged();
}

public class Connect { 
     private static boolean myBoolean;
     private static List<ConnectionBooleanChangedListener> listeners = new ArrayList<ConnectionBooleanChangedListener>();

     public static boolean getMyBoolean() { return myBoolean; }

     public static void setMyBoolean(boolean value) {
         myBoolean = value;

         for (ConnectionBooleanChangedListener l : listeners) {
             l.OnMyBooleanChanged();
         }
     }

     public static addMyBooleanListener(ConnectionBooleanChangedListener l) {
         listeners.add(l);
     }
}

Then, wherever you want to listen to changes of the boolean, you can register a listener:

Connect.addMyBooleanListener(new ConnectionBooleanChangedListener() {
    @Override
    public void OnMyBooleanChanged() {
        // do something
    }
});

Adding a method to remove listeners is left as an exercise. Obviously, for this to work, you need to make sure that myBoolean is only changed via setMyBoolean, even inside of Connect.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download