Android Observers and Observables – How to Update Activities Automatically Upon Data Changes!

Extending the Android Observer and Observable Classes for Auto Updates

The beauty of using an object oriented language such as Java is the ability to extend other classes on your object. Two awesome example of this are the Java Observer and Observable classes. By extending the Observable class on your data object (model), you are able to assign Observers which listen for changes in said data model. When the data changes, the Observer is notified automatically and fires its update() method.

Refresh your Views in the update() Method

The update() method is an obvious place to put your code which refreshes the views impacted by the changes in data, this is where the linkage between the views and the data model occurs (usually in the Android Activity). The beauty of using the Observer and Observable classes is that the data model, views and controller (the Activity that updates the views) are all separated. That is, you can use the data model for whatever you want, if you change the views it won’t break the data model and vice versa. This makes your app much simpler to understand and easier to update later down the road.

How this Example Works

Below I’ve created a very simple, but hopefully effective example which demonstrates using Observers and Observables to automatically update views upon changes in data. The Activity ObserverExample is registered as on Observer on the data model Score and acts as the controller in our application. When the Score changes, ObserverExample is notified and the method update() fires, within that method the app fires another method setScore() which refreshes the score to the new values.

Note this method of “wiring” up an app is called the Model-View-Controller paradigm. As you can see from the code, it simplifies the app by ensuring no parts of the app are tightly coupled to the other, this is important for creating simplistic and extensible code.

Take a look at the code below, also be sure to grab the .ZIP of the Eclipse Project and try it for yourself!

The main Activity

The data model

Layout XML file activity_main.xml

Download the .ZIP of the Eclipse Project here! Enjoy and please leave me feedback in the comments, I appreciate it!

Share this:
Share on Google+Share on FacebookTweet about this on TwitterShare on LinkedIn
Ryan Park
Ryan is a self-taught Java and Android developer who's passionate about creating software that's simple yet powerful. When Ryan's not on the computer he's working out, kickboxing or petting his tiny dogs...
Ryan Park on FacebookRyan Park on GoogleRyan Park on LinkedinRyan Park on Twitter

3 thoughts on “Android Observers and Observables – How to Update Activities Automatically Upon Data Changes!

Leave a Reply

Your email address will not be published. Required fields are marked *