I'm trying to create a custom listener for a variable that changes continuously and want to keep a track of it and update my display (TextView) each time a change is registered. I've taken reference from In Android, how do I take an action whenever a variable changes? But, this runs only once. I want it to continuously track the changes and update display upon state change.
2 Answers
I can think many ways of doing this, but I think the simplest one is just create a Wrapper of the variable you wan't to "listen" to, implemente a getter and a setter, and of course the listener interface. Lets supose you want to "listen" to an int variable:
public interface OnIntegerChangeListener
{
public void onIntegerChanged(int newValue);
}
public class ObservableInteger
{
private OnIntegerChangeListener listener;
private int value;
public void setOnIntegerChangeListener(OnIntegerChangeListener listener)
{
this.listener = listener;
}
public int get()
{
return value;
}
public void set(int value)
{
this.value = value;
if(listener != null)
{
listener.onIntegerChanged(value)
}
}
}
Then you just use it:
ObservableInteger obsInt = new ObservableInteger();
obsInt.setOnIntegerChangeListener(new OnIntegerChangeListener()
{
@Override
public void onIntegerChanged(int newValue)
{
//Do something here
}
});
Each time you change the value (with Set(...) ), the listener, if not null, will be called-

- 611
- 3
- 9
Another option you can take, maybe more complicated, is to create a service (http://developer.android.com/guide/components/services.html)
Basically, you create an "activity" in the background where you create a loop that is checking regularly if the variable has changed or not the value (you will need to create a public method on your activity to do so), if the variable has change you can make an action.
For me the other option proposed here sounds more sensible for me, but you mentioned that is not working for you.

- 930
- 2
- 17
- 36