Model View Controller Pattern in Android (Part 2)

Building the view

As an example for a I want to build a simple RPN Calculator, a Reverse Polish Notation calculator. A RPN calculator is a calculator where you enter all your numbers using an enter key and than the operations pull the numbers back off a stack of operations. So for example, if you wanted to do three plus five you would say three enter, five enter, plus and it would pull the three and the five off, add them, make eight, and then it it would put that back on the stack. And so if you then said six plus you’d get 14.
For building the user interface you obviously need some buttons a text label area so you can have a display in the calculator, and things like that. In the following figure the UI is shown for an Android 2.2 device.

Calculator View for Android 2.2 in Landscape Mode
Calculator View in Portrait Mode
In Android, objects in the view layer are inflated from XML within a layout file. The layout file of the  calculator consists of a TableLayout with an EditText field and rows of buttons:

<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
        <requestFocus android:layout_width="match_parent" />
        android:layout_weight="1" >
            android:text="@string/button_clear_text" />
            android:text="@string/button_root_text" />
            android:text="@string/button_devide_text" />
            android:layout_weight="1" >
            android:layout_weight="1" >
            android:text="@string/button_five_text" />
            android:text="@string/button_six_text" />
            android:text="@string/button_minus_text" />
         android:layout_weight="1" >
            android:text="@string/button_one_text" />
         android:layout_weight="1" >
            android:text="@string/button_point_text" />


Model View Controller Pattern in Android (Part 1)

1. Introduction

Design principles like code reusability and separation of concerns are the central ideas behind the Model View Controller pattern. Like other Java UI toolkits Android UI framework is organized around this pattern.

1.1 Model View Controller

But what is model view controller? The main idea of model view controller is to divide all objects in one of three "camps":
  • the model "camp"
  • the controller "camp" and
  • the view "camp"

The three "camps" of the Model-View-Controller

But what are these three Camps?

1.2 The Model

The model camp is what your application does. For example, if you're building a spaceship shoot 'em up game this is where the spaceships are in outer space, what planets are and where they are. Which guns every ship has and how much damage it can take and so on.
Those are all part of what the program is. It represents space ships in outer space. That's its model.
But notice the model doesn't know anything about where the ships are on the screen. The ship on the screen has nothing to do with the model. That's where the controller and the view comes in.

1.3 The Controller

The controller you can think of as the objects that control how the model is presented on the screen. It's a kind of a glue. It's the thing that takes the space ship's position in outer space and figures out how to show this on screen.

1.4 The View

And the view is the controller's minions. The view is just objects that your controller uses to do what it does, to get this thing on screen. We try to make objects in the view camp as generic as possible, like buttons and sliders. They come from Google and they don't know absolutely nothing about the application they're appearing. It's up to the controller to take these generic minions and use them to do what needs to be done to display the model on screen.

1.5 Communication between the Camps

Once you have all these three camps than it's all about managing the communication between the camps. What communication is allowed and how we achieve that communication.

Let's talk about the controller talking to the model. This is a controller object that wants to send a message to an object in the model and that is 100% allowed. Green arrow going in that direction.
The controller always talk directly to the model. Because it's the controller's job to get that model on screen somehow so it needs to have full access to the model. The green arrow goes one way, so it's the controller knowing about the model.

The Controller "talking" to the model

Between the camps there are lines that look like road markers and from the side from the controller to model theres a dashed line that means cross over this line any time you want.

What about the controller talking to its minions - also green arrow. The controller is responsible for getting the model on screen it has got to have full ability to do anything it wants with those views, e.g. set them up, arrange them on screen, communicate data to the view etc.  So that arrow is also green. That side of the road is also a dashed line.

The controller is allowed to talk to the view

How about the the model and the view. They should never talk to each other. I'm sure that you can  understand why the model never talks to a view. The model is user interface independent. You could have a model for a space shout em up game where the user interface is command line. It would be kind of silly but you could.

The other way some people say I want to build a custom view that knows all about my model so I can display it. Well that sounds attractive but the reason why this is not such a good idea is reuse. Because when you write that custom thing tied to the model. Whenever you change the model you have to rewrite that custom thing. Those things are linked in a way that the view can't be reused and also the model can't be reused with a different UI. It's better to put that code in the controller. And try to build a more generic UI object.
The other reason is that if you have a view talking to the model. Now you have everybody talking to the model. Now the model is al little bit like under siege. And when you try to figure out what's going on inside my application it's a lot easier when you know the only the controller is talking to you model.

How about the view speaking to its controller? As mentioned before the objects in the view are generic objects (buttons & sliders) that come from Google and they don't know absolutely nothing about the application they're appearing. So the communication between the view and the controller has to be "blind", which means that the view can not know which class of object it is talking to. Because the communication is "blind" it has to be structured. This blind and structured communication is realized via a pattern quite common in the Android libraries, the callback.

The view talks to the controller in a"blind" and structured way

To define a callback extension point, a class defines two things. First it defines a Java Interface (a Listener) that describes, but does not implement, the callback action. It also defines a setter method that takes, as an argument, an object implementing the interface.

Button is a subclass of View, which defines an interface named OnClickListener and a method named onClick. The interface defines a single method, onClick. When a Button receives a click, and if the listener is installed, that listener's onClick method is invoked. In the activity the code would look like the following snippet:

((Button) findViewById(R.id.button_id)).setOnClickListener(
        // this is an anonymous class
        new Button.OnClickListener() {
            public void onClick (View v) {
                digitPressed((Button) findViewById(R.id.button_id), display); 

/** Handle the onClick Event */
void digitPressed(Button button, TextView textView) {
         // Handling onClick event goes here ... 

This pattern is used by the Android Framework pervasively. It is also used for the communication between model and the controller, when the model is updated. This means that there is also a "blind" communication between the model and the controller.

The model talks to the controller "via" the callback


Automatic Login in iOS 6

With the update from iOS5 to iOS6 Apple changed the Captive Network Support, so that the option automatic Login in the WLAN / Wifi options is no longer available. After the Update to iOS6 it was impossible for me to login to my company WLAN / Wifi Access Point using my iPhone. To get a workaround to this problem I wrote the App “Wlan Aid”. It uses the Captive Network Programming Interface. The only thing a User has to do is to put in the SSID of the WLAN he wants to join. Than the app calls the Function CNSetSupportedSSID with this SSID as input parameter. With this function my app registers the SSID with Captive Network Support, thereby assuming responsibility for authenticating with this network. And that’s it. After my application has registered the SSID the web sheet of Captive Network Support is suppressed, and the user can complete the authentication in Safari. In Safari it is possible to accept any unauthorized certificate and so on.


When to Use Class Methods in Objective C ?

A class in Objective-C can declare two types of methods: instance methods and class methods. An instance method is a method that is triggered when a message is sent to a particular instance of the class. In other words, before you call an instance method, you must first create an instance of the class. Class methods, by comparison, do not require you to create an instance. They are triggered when a message is sent to a class. In other languages, i.e. Java, class methods are called static methods.

One common use for class methods in Objective C or static methods in Java is to provide utility methods, i.e mathematical functions. A common example for static methods in Java are the static methods in java.lang Math. In Objective C you can often rely on pure C functions for utility methods, such as mathematical functions, so that you won't find many utility class methods in the frameworks, i.e. the fondation framework.

In Objective C you typically use class methods as (static) factory methods to create new instances of the class, which is an alternative to the object allocation and initialization procedure. For example NSString contains some very useful factory methods (like + (id)StringWithFormat:(NSString *)format) that return autoreleased NSString objects.

In his Book Effective Java (2nd Edition): A Programming Language Guide Joshua Bloch explained the advantages of of using factory (class/static) methods.Although Bloch's book was initially written for Java, most of his ideas are applicable to other object oriented languages.
One advantage of static factory methods is that, unlike constructors, they have names. A static factory with a well-chosen name is easier to use and the resulting client code easier to read. 
Most of the factory methods in the apple frameworks are good example for good naming convention as you can see in NSDate. You don't need much documentation to understand which objects are created by the following methods:

+ (id)dateWithTimeInterval:(NSTimeInterval)seconds sinceDate:(NSDate *)date
+ (id)dateWithTimeIntervalSince1970:(NSTimeInterval)seconds
+ (id)dateWithTimeIntervalSinceNow:(NSTimeInterval)seconds
A second advantage of static factory methods is that, unlike constructors, they are not required to create a new object each time they’re invoked.  
You can ensure that a certain class vends a singleton instance. The factory only creates an instance if the the instance doesn't exist. This is achieved with the with the following code snippnet:

static AccountManager *DefaultManager = nil;

+ (AccountManager *)defaultManager {
    if (!DefaultManager) DefaultManager = [[self allocWithZone:NULL] init];
    return DefaultManager;


Exception Breakpoint in Xcode

In Xcode 4 when an exception is raised (wether it is ,unrecognized selector sent to instance‘ exception or an 'out of bounds' exception or another exception) the exception goes up the call stack looking for someone who can handle it. And what normally happens is that no on handles it  and the exception percolate up the call stack all the way up to main. The program just crashes and you lost the call stack information.
To avoid this, Xcode provides a very important breakpoint which gonna break every time an exception is raised and Xcode shows in the main code window the line of code on which that exception would raise.

You can add an Exception Breakpoint by opening the Breakpoint Navigator.

Breakpoint Navigator

Than you have to click the Plus Button in bottom left corner:

Add Exception Breakpoint

After clicking Add Exception Breakpoint menu item, you will see this breakpoint configuration view open up:

Click Done
After clicking the Done button and you will the new Exception Breakpoint in your list of breakpoints.

I recommend setting that exception on all the time on in Xcode because you pretty much always want to have this exception happen right a the line of code.