I have a simple Android application that has an Activity with an Observable object, foo, inside of it. I have a private inner class implementing Observer in my activity that updates the GUI with the argument passed to update. I attach the Observer with foo.addObserver when creating the activity.
However, my observer is only notified once, then it receives no more updates. I’ve stepped into foo and my observer is deleted when it tries to send out a 2nd notification. Has anybody experienced this before? What could be causing this? I don’t know how to troubleshoot this any further. This seems so simple. There’s probably something outside of this that I’m doing that is causing this? If anybody has any ideas, I can reveal more of my application.
Relevant code for this is below (sans parameters and scope)
Activity
onCreate
...
foo = new Foo();
foo.addObserver( new FooObserver() );
...
class FooObserver implements Observer {
update()
updateGUI();
Foo
arbitraryMethod()
...
setChanged();
notifyObservers( argument );
The (embarrassing) problem I was having is that I had multiple instances of Foo and was only registering the listener one a specific instance of the object without remembering that I have created multiple instances of the object, which is why the array of Observers was empty after the first update; I was looking at a different object!
There are many solutions to this, but the one that works in my case is to make the object a singleton.