Chapter 5. Patterns

 

In this chapter, you’ll read about different development patterns you can use inside Android.

Hack 20 The Model-View-Presenter pattern: Android v1.6+

You’ve most likely heard of the MVC (Model-View-Controller) pattern, and you’ve probably used it in different frameworks. When I was trying to find a better way to test my Android code, I learned about the MVP (Model-View-Presenter) pattern. The basic difference between MVP and MVC is that in MVP, the presenter contains the UI business logic for the view and communicates with it through an interface.

In this hack, I’ll show you how to use MVP inside Android and how it improves the testability of the code. To see how it works, we’ll build a splash screen. A splash screen is a common place to put initialization code and verifications, before the application starts running. In this case, inside the splash screen we’ll provide a progress bar while we’re checking whether or not we have internet access. If we do, we continue to another activity, but if we don’t, we’ll show the user an error message to prevent them from moving forward.

To create the splash screen, we’ll have a presenter that will take care of the communication between the model and the view. In this particular case, the presenter will have two functions: one that knows when we’re online and another to take care of controlling the view. You can see the project structure in figure 20.1.

Figure 20.1. MVP project structure

Hack 21 BroadcastReceiver following Activity’s lifecycle: Android v1.6+

Hack 22 Architecture pattern using Android libraries: Android v1.6+

Hack 23 The SyncAdapter pattern: Android v2.2+