Category: Android

Android is an open source and Linux-based operating system for mobile devices such as smartphones and tablet computers. It was developed by the Open Handset Alliance, led by Google, and other companies.

Android programming is based on Java programming language so if you have basic understanding on Java programming then it will be a fun to learn its application development. Its applications are usually developed in the Java language using the Android Software Development Kit. Once developed, the applications can be packaged easily and sold out either through a store such as Google Play, SlideME, Opera Mobile Store, Mobango, F-droid and the Amazon Appstore.

Android Distribution

It powers hundreds of millions of mobile devices in more than 190 countries around the world. It’s the largest installed base of any mobile platform and growing fast. Every day more than 1 million new devices are activated worldwide.

This category will help you learn all the basics and advanced areas to enable you become a programming ninja.

ButterKnife  – A Viewbinding library for Android

ButterKnife  – A Viewbinding library for Android

In this post, we will detailed look into ButterKnife, a viewbinding library for android. Also demonstrate how it’s work, how to integrate and use in your android app development to make your development faster.

Let’s get started!

What is Butterknife?

Butter Knife is small, simple and lightweight, and it makes life as a developer easier. It is developed by Jake Wharton. It makes your code less and more clear. It is time saving to write repetitive lines of code.

ButterKnife is a view binding library that uses annotation to generate boilerplate code for us.

It allows developers to perform injection on arbitrary objectsviews and OnClickListeners so they can focus on writing useful code. Consider Android Butter Knife a reduction library. It replaces findViewById with @BindView() and set^^^^Listener calls with @onClick() making code cleaner and more understandable. Butter Knife enables focus on logic instead of glue code and reduces development time by reducing redundant coding.

Getting Started

It is easy to use butterknife in your project. Just add the following dependencies in your build.gradle(module: app) and sync your project!

Butterknife supports Field and method binding for Android views which uses annotation processing to generate boilerplate code for you.

  • Eliminate findViewById calls by using @BindView on fields.
  • Group multiple views in a list or array. Operate on all of them at once with actions, setters, or properties.
  • Eliminate anonymous inner-classes for listeners by annotating methods with @OnClick and others.
  • Eliminate resource lookups by using resource annotations on fields.

All you need to write in these methods is the following:



In both the cases Butter Knife binds to the specified Android Activity or Viewtargets to correctly act on the injections specified in these classes. All the view finding lines of code and the action listeners are implemented elsewhere, leaving these methods as clean as possible.

Binding Views, Resources and Event Listeners

Butter Knife replaces the standard findViewById call with @BindView, followed by a view ID and it automatically casts the corresponding view in the corresponding layout. This representation of the code makes it more compact and readable.

Here’s an example of this “injection”:

You can do the same with app resources like StringDrawable and dimensions (dimenvalue , etc).

Butter Knife also makes setting event listeners of Android layout Views easy and removes the listeners implementation from the key onCreate and onCreateViewmethods.

You can refer to the Butterknife Documentation on this link


Android Butter Knife helps you create cleaner and tidier code, handling a lot of the ugly boilerplate code that Android has become infamous for. Have you tried it in your projects? Thanks for reading this article. Be sure to share this article if you found it helpful.

Happy Coding!

Android Data Binding

Android Data Binding

Android provides data binding library that helps in creating apps with less glue code to bind application logic and layouts. With data binding, you don’t need to find views in activities or fragments, set view attributes to properties of data model object and add event handlers to views, all this is taken care of by data binding framework using the data binding component classes and data binding expressions that you define in layouts.

Data binding compiler tool generates necessary code to make the binding work using xml layout and data binding component classes defined using annotations.

Project Setup

The Data Binding Library offers both flexibility and broad compatibility – it’s a support library, so you can use it with all Android platform versions back to Android 2.1 (API level 7+). To use data binding, you need to enable it by adding below configuration to modulebuild.gradle file.

If you have an app module that depends on a library which uses data binding, your app module must configure data binding in its build.gradle file as well.

Data Binding

To use data binding framework, first you need to create data model object, then define your activity layout with data binding elements and expressions. Lets create a simple User Model.

Notice in the below example that layout’s root element is layout and data model object variable is declared using variable element under data element.

The user variable within data describes a property that may be used within this layout.

Expressions within the layout are written in the attribute properties using the “@{}” syntax. Here, the TextView’s text is set to the firstName property of user:

By default, a Binding class will be generated based on the name of the layout file, converting it to Pascal case and suffixing “Binding” to it. The above layout file was main_activity.xml so the generated class was MainActivityBinding. This class holds all the bindings from the layout properties (e.g. the user variable) to the layout’s Views and knows how to assign values for the binding expressions.The easiest means for creating the bindings is to do it while inflating:

If you run the above example, it will display data object value in UI widget. But using @{} expression as shown above will just bind the value of the property of data object to the attribute of View. But it won’t refresh the UI widget with the changed value of the property of the object and it won’t populate the data object with user entered or modified value into the UI widget.

Data binding does not support include as a direct child of a merge element. For example, the following layout is not supported:


Variables may be passed into an included layout’s binding from the containing layout by using the application namespace and the variable name in an attribute:

Here, there must be a user variable in both the name.xml and contact.xml layout files.


Data Binding is a powerful tool to reduce boilerplate code, when binding or referencing views that show data.  In heavy UI intensive application like Calculator, you will find yourself repeating almost the line of code over and over again. Data binding also offers Two Way Data Binding, which I will cover later. Remember to share and leave comments 🙂

I hope you start using Data Binding in your Android Apps 🙂

Happy Coding!

Setting up Travis CI in Android

Setting up Travis CI in Android

If you are developing using TDD you should run your tests to be sure that you don’t break something in every TDD phase. But we are not perfect and we can commit changes that break our system and we should have something that can alert us if we are doing something wrong asap. This is going to be a short guide on getting set and ready with Travis CI in Android. Before we continue, you need to have an Android Studio project already set up. Now let’s get down to business.


  • Create a github repo for your project
  • Head over to the root of your project and create a .travis.yml (More on this later)
  • Still at the root of your project, create a folder/directory called licenses; this directory will help in exporting your license agreements such as sdk license agreement from your local machine to the build environment.
  • Now head over to your sdk location and locate a folder/directory called licenses, copy its contents then go ahead and paste them inside the licenses folder/directory you created previously at your project root.
  • You’re now set up, just do a git init, add all your files to git then push your code to Github.

Setting up Travis CI

Here is where Continous Integration comes into play. Every time that you push changes into a branch in your system you can check if everything is ok before you merge this branch into Master (assuming you are using git). What to check? Well, this is up to you and your team members to decide.

I keep my promises! , lets now talk about .travis.yml mentioned earlier. So this is just a file that tells your build machine how it should be configured and also provides the necessary tools and information to get your build system up and running.

So how does this file look like? Here’s the code, you can copy paste it but ensure you go through it to have a grasp of what’s going on.

You can decide to paste it directly to your code then commit and push the changes or paste it in your Github Repo then pull the changes, either of these two will work fine.

Travis provides the service for free but your repo in Github must be public and the free URL is different from the premium URL.

After visiting Travis, sign in with Github. Search for your Github repo then add it. Travis will go to your repo, locate the .travis.yml file and do the rest. Hopefully, if you followed every step correctly, your build should be successful and the repo should turn green with the badge at the top indicating build passing.


It’s awesome looking at that badge from your repo. So to add it to your repo, go ahead and click on it. A pop up will show with the url of the badge. Copy the url then paste it in your README file. Here’s an example of how the file should look like inside your README file.

Hooray! Your CI should now be up and running. Thanks for your time.

Happy Coding!

Android Architecture Patterns : Model-View-ViewModel

Android Architecture Patterns : Model-View-ViewModel

Since joining Twiga Foods, I have been involved majorly in the development of our Android App. During the design and development of the first version of the app, there was really no Architecture Pattern that was followed. Many changes were made after deployment, and they learned one important lesson: They needed an architecture pattern that allows fast reaction to design changes! The solution we chose in the end was Model-View-ViewModel after some discussions. Discover with me what MVVM is; how we are applying it at Twiga Foods for our second version and what makes it so perfect for us.

I decided to share the Harvest and Scouting Process Image, above in the Featured Image 🙂 Courtesy Twiga Foods

The Model-View-ViewModel Pattern

The main players in the MVVM pattern are:

  • The View – that informs the ViewModel about the user’s actions
  • The ViewModel – exposes streams of data relevant to the View
  • The DataModel – abstracts the data source. The ViewModel works with the DataModel to get and save the data.

At a first glance, MVVM seems very similar to the Model-View-Presenter pattern, because both of them do a great job in abstracting the view’s state and behavior. The Presentation Model abstracts a View independent from a specific user-interface platform, whereas the MVVM pattern was created to simplify the Event Driven programming of user interfaces.

If the MVP pattern meant that the Presenter was telling the View directly what to display, in MVVM, ViewModel exposes streams of events to which the Views can bind to. Like this, the ViewModel does not need to hold a reference to the View anymore, like the Presenter is. This also means that all the interfaces that the MVP pattern requires, are now dropped.

The Views also notify the ViewModel about different actions. Thus, the MVVM pattern supports two-way data binding between the View and ViewModel and there is a many-to-one relationship between View and ViewModel. View has a reference to ViewModel but ViewModel has no information about the View. The consumer of the data should know about the producer, but the producer – the ViewModel – doesn’t know, and doesn’t care, who consumes the data.

Model-View-ViewModel using RxJava

The event driven part required by MVVM is done using RxJava’s Observables. Here’s how you can apply MVVM with the help of RxJava:


The DataModel exposes data easily consumable through event streams – RxJava’s Observables. It composes data from multiple sources, like the network layer, database or shared preferences and exposes easily consumable data to whomever needs it. The DataModels hold the entire business logic.

Our strong emphasis on the single responsibility principle leads to creating a DataModel for every feature in the app. For example, we have a FarmerModel that composes its output from the API service and database layer. This DataModel handles the business logic ensuring that the latest farmers from the database are retrieved.


The ViewModel is a model for the View of the app: an abstraction of the View. The ViewModel retrieves the necessary data from the DataModel, applies the UI logic and then exposes relevant data for the View to consume. Similar to the DataModel, the ViewModel exposes the data via Observables.

We learned two things about the ViewModel the hard way:

  • The ViewModel should expose states for the View, rather than just events. For example, if we need to display the name and the phone number of a Farmer, rather than creating two streams for this, we create a DisplayableFarmer object that encapsulates the two fields. The stream will emit every time the display name or the phone number changes. This way, we ensure that our View always displays the current state of the Farmer.
  • We should make sure that every action of the user goes through the ViewModel and that any possible logic of the View is moved in the ViewModel.


The View is the actual user interface in the app. It can be an Activity, a Fragment or any custom Android View. For Activities and Fragments, we are binding and unbinding from the event sources on onResume() and onPause().

If the MVVM View is a custom Android View, the binding is done in the constructor. To ensure that the subscription is not preserved, leading to possible memory leaks, the unbinding happens in onDetachedFromWindow.

Testability Of The Model-View-ViewModel Classes

One of the main reasons why we love the Model-View-ViewModel pattern is that it is so easy to test.


The use of inversion of control pattern, heavily applied in our code, and the lack of any Android classes, facilitate the implementation of unit tests of the DataModel.


We see the Views and the unit tests as two different types of consumers of data from the ViewModel. The ViewModel is completely separated from the UI or any Android classes, therefore straightforward to unit test.

Consider the following example where the ViewModel just exposes some data from the DataModel:

The tests for the ViewModel are easy to implement. With the help of Mockito, we are mocking the DataModel and we control the returned data for the methods used. Then, we make sure that when we subscribe to the Observable returned by getSomeData(), the expected data is emitted.

If the ViewModel needs access to Android classes, we create wrappers that we call Providers. For example, for Android resources we created a IResourceProvider, that exposes methods like String getString(@StringRes final int id). The implementation of the IResourceProvider will contain a reference to the Context but, the ViewModel will only refer to an IResourceProvider injected.

We are creating model objects to hold the state of the data. This also allows a higher degree of testability and control of the data that is emitted by the ViewModel.


Given that the logic in the UI is minimal, the Views are easy to test with Espresso. You can also using libraries like DaggerMock and MockWebServer to improve the stability of our UI tests.

Is MVVM The Right Solution?

We fully decided and agreed to use MVVM. We have seen that since the View is just a consumer of the ViewModel, it was easy to just replace different UI elements, with minimal, or sometimes zero changes in other classes 🙂

We have also learned how important separation of concerns is and that we should split the code more, creating small Views and small ViewModels that only have specific responsibilities. The ViewModels are injected in the Views. This means that most of the times, we just add the Views in the XML UI, without doing any other changes. Therefore, when our UI requirements change again, we can easily replace some Views with new ones. Super Cool!!!


MVVM combines the advantages of separation of concerns provided by MVP, while leveraging the advantages of data bindings. The result is a pattern where the model drives as many of the operations as possible, minimizing the logic in the view.

Now, we can be proud of an app that has proven its resistance to another redesign. We are finally close to being able to call our Twiga App [DMS] a mature app.

I would love to hear your views and opinions on the different Architecture Patterns you have used before, and why you chose them. Remember to share 🙂

Happy Coding!

Layout Preview with Tools DesignTime Attributes

Layout Preview with Tools DesignTime Attributes

This is a short tip for Android Studio users. Many people know this, but I thought to still share for those that don’t know.

As developers, when we’re building a UI layout in Android, it’s common desire to want to preview what we’re designing right?

We usually want to add that sample data, like android:text="Test Test" to see how exactly it will look in our layout. Many times, we forget to remove such sample data. It’s even more stressful when you’re building a list. You have to run the app to see what your list looks like.

Well, designtime attributes are here to help.

Designtime attributes? What are they?

Designtime attributes are attributes that are used only in rendering the Android studio layout preview, they have no impact at runtime. Designtime attributes aren’t new in Android studio. They’ve been around since Android Studio 0.2.11.

Designtime attributes are specified by the use of the tools namespace in Android XML layouts.

Using designtime attributes

a. Declare tools namespace.

To use the designtime attributes, you need to first declare the tools namespace within the root tag of your layout. Your layout will look something like:

All tools attributes get stripped out at compile time by AAPT, and that’s how they have no effect at runtime.

b. Replace android namespace with tools

Now that you have declared the namespace, you can replace almost any android xml attribute with tools, for the designtime.

For example, let’s say we wanted to test our text wrapping and see how our textview would look with a very long text, we would do something like:

Note the tools:text attribute we used instead of the usual android:text

Interesting uses with ListViews and RecyclerViews

Now, let’s look at further examples of designtime attributes.

1. ListView

You can use designtime attributes to preview what the list will look like if you’ve designed your list item, using the listitem attribute. For example:

2. RecyclerView

You can still do the same in a RecyclerView with ease. For example:

Points to note about designtime attributes

  • It works ONLY with Android framework attributes. That is, it doesn’t work with custom attributes yet.
  • You can use them together with regular layout android attributes. For example:

  • They only work within Android layout files. You can’t use designtime attributes in menus, drawables, etc.

References and further reading

If you have any comments, suggestions or corrections, or you want to share your use of designtime attributes, feel free to drop a comment below. Please share if you found this useful.

Happy Coding!