Tag Archives: Android

Rebuilding a legacy app from the scratch (II): Adding Continuous Integration with Travis CI

Continuous Integration (CI) is a Software engineering practice where developers in a team continuously integrate their work in the main stream of source code at least once a day.

Why?

The main goal of the CI practice is to reduce the integration problems that quite often happen when we have a team of several people working in different features and parts of our system. The sooner we integrate our code the easier is to identify problems like dependencies between modules, compilation issues, regression, duplication in code, etc, etc.

How?

Continuous Integration is overall an attitude and good Software practice. In order to achieve it we need some tools and organisation.

First of all we need our source code in a repository, in our case to maintain MadridBus app we are using Github in a public repository.

Next we need a platform to perform the automatic builds of our code every time we push code to the repository. For our app we are going to use Travis CI. Travis is a hosted distributed CI platform, it’s free for public repositories and it’s quite easy to integrate and configure in our project.

Finally we need a good suite of Unit Test that are going to run every time a new build is launched, that as we mentioned before is going to happen for each push that we make in our repo. We will talk about the testing strategy in further posts but in the mean time you can take a look to one of my previous posts.

TRAVIS CI configuration

So first thing is going to https://travis-ci.org/ and we sign in with the Github account travisci-mascot-1-bc6a3179f3e8e1ab1456634bd55a448awhere we have allocated the Android project.

Then we are going to select the project we want to set up with continuous integration and that’s pretty much it, we can start building!

But not so fast, probably your build is going to fail as we need to set it up properly for Android projects, and the way to do this is adding the “.travis.yml” configuration file.

Below you can see the current MadridBus Travis configuration file:

language: android

jdk: oraclejdk8

cache: false

sudo: true

env:
  global:
    - ANDROID_API_LEVEL=25
    - ANDROID_BUILD_TOOLS_VERSION=25.0.0
    - ANDROID_ABI=armeabi-v7a
    - ADB_INSTALL_TIMEOUT=20 # minutes (2 minutes by default - see #247)

android:
  components:
    - platform-tools
    - tools
    - build-tools-$ANDROID_BUILD_TOOLS_VERSION
    - android-$ANDROID_API_LEVEL
    # Google Play Services
    - extra-google-google_play_services
    # Support library
    - extra-android-support
    # Latest artifacts in local repository
    - extra-google-m2repository
    - extra-android-m2repository
    # Specify at least one system image
    - sys-img-armeabi-v7a-android-$ANDROID_API_LEVEL

# Emulator Management: Create, Start and Wait
before_script:
  - echo no | android create avd --force -n test -t android-21 --abi armeabi-v7a
  - emulator -avd test -no-skin -no-audio -no-window &
  - android-wait-for-emulator
  - adb shell input keyevent 82 &

script:
  - android list target
  - ./gradlew connectedAndroidTest

licenses:
    - 'android-sdk-preview-license-.+'
    - 'android-sdk-license-.+'
    - 'google-gdk-license-.+'

Right, so let’s take a look to the interesting parts. As you can see in the first two lines we are specifying the project type with “language: android” and the JDK version 8 to be used to compile with “jdk: oraclejdk8”.

Right now by default Travis will build our project with Android SDK 24, so if we want to install and build with a latest SDK and use any other additional component we need to specify it as we can see it in the section “components” under the “android” tag.

As you can see in the example we are indicating that we want to use Build Tools version 25.0.0, Android SDK 25 and also that we are using Google Play Services adding “extra-google-google_play_services”. One important thing here is to tell Travis to accept all the licences when installing additional components, otherwise the build will fail. For this we are adding the section “licenses” as you can see above.

Finally we want to launch an emulator so we can run the tests. To accomplish this we are adding the section “before_script” where we are launching and waiting until is running for the emulator with the image type as configured in the field “sys-img-armeabi-v7a-android-$ANDROID_API_LEVEL”.

And that’s it! We just need to push new code to the repository and Travis will build automatically the project and run the tests for us.

In next posts we will see how to add our testing strategy including Unit Tests with JUnit, Integration Tests with Espresso, mocking with Mockito, etc.
Stay tunned!

Tagged , , ,

Introduction to RxJava for Android by examples (I)

rxjava

Reactive programming is one of the hottest topics amongst the Android community these days. Lot of big guys in the industry are embracing and using RxJava in their platforms and applications, even Google has release their own version of a reactive library called Agera.

One of the problems of Rx programming is the initial learning curve, the complexity of the paradigm itself and the extension of the library operators and classes.

The goal of this post is to make a very simple and easy to understand introduction with some examples and be able to start programming and design our apps using RxJava.
 

What is RxJava?

RxJava is just a library that implements ReactiveX extensions, which basically facilitate the implementation of  asynchronous programming using observables data streams.

It can be described as a combination of the Observer (there is one entity emitting data and one or many listening or it) and Iterator (the data flow are dispatched in onNext events sequences)  patterns using the Functional Programming paradigm (we get data in declarative style methods and avoiding mutable objects).

RxJava is one of the language implementations of the ReactiveX libraries. At the moment there are also other versions available for languages like JavaScript, C#, C++, Swift, Kotlin, etc…
 

Why RxJava?

So if there is the learning curve and complexity issue, why to bother learning RxJava? These are some of the main reasons:

  • Abstraction of complexity of async data flows and events. It’s quite common to fall into the hell of nested and multiple listeners, the hell of multiple events from everywhere when using an event bus, etc. With RxJava we can simplify all this using just asynchronous stream of transformable data.
  • Filtering, composition, transformation. Thanks to the massive amount of operators we can easily transform any stream of data transmitted. As we will see later we can filter, combine, transform, create, etc. any kind of data stream.
  • Error handling.  Very straightforward error handling by centralising in a single callback method any error, stopping the data sequence.
  • Easy testing. Having a single source/destination of the data source and testing helper classes make it quite easy to test.
  • Light and high performance. RxJava is light and fast, at the moment it weights around 1 MB and it’s quite fast streaming our data.

 

The key components

So let’s take a quick look to the key elements that compose the RxJava library.

The Observable

This is the data source, the object that will be emitting the sequences of data items that the entities who are interested in the data they provide, will be subscribing.  It implements all the operators mentioned before to be able to transform the data streams. Observables can be divided in two types: “Hot” observables which might emit data as soon as they are created  and “Cold” observables which wait until an Observer subscribes to it.

The Observer

This is the type of object that will be subscribing and “observing” the data emitted by the Observable, they will “react” somehow using the data provided. Typically they implement the three main events OnNext, OnError, OnComplete as we will see later.

More info in the official reference here.

Operators

These is one of the key and most powerful features of RxJava. There are quite a lot operators of different types that will help us to manipulate and transform in many ways the data streams. We can group them in different categories such as Creating, Transforming, Filtering, Combining, Mathematical, etc.

For a complete list of operators take a look to the documentation following this link.

Schedulers

The Schedulers will help us to implement multithreading in our data streaming. Calling the Observable method “SubscribeOn” and indicating one of the Schedulers we can select in which thread the Observable will do it’s data stream job. On the other hand, calling the method “ObserveOn”, will set up the thread where we will be receiving and observing its data stream.

In RxJava the most common Schedulers are “NewThread” (create a new thread for each job), “io” (for input/output operations), “computation” (event-loops, callbacks processing, etc), “immediate” (perform the job immediately in the current thread), etc.

Subject

A Subject is object that is able to act as Observable and Observer. It can emit data streams and at the same time can subscribe to another data stream source (Observable), so we can think in it like a sort of bridge between two data streams.
 

Example 1: Simple subscription to a source of data

For our first example, we have a method that create a list of numbers and in order to simulate a long operation, we have added a 100 milliseconds thread pause in the loop.

The method look like this:

private List<Integer> getOddNumbers() {
    List<Integer> numbers = new ArrayList<>();
    for(int i=0; i<100; i++) {
        if(i%2 == 0) {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    return numbers;
}

 
Now we create the Observable that is going to emit that list of numbers. To accomplish this, in this example we use the “fromCallable()” method that is going to build an observable which will emit the list of numbers retrievedby the callable method:

private Observable<List<Integer>> getOddNumbersObservable() {
    return Observable.fromCallable(new Callable<List<Integer>>() {
        @Override
        public List<Integer> call() throws Exception {
            return getOddNumbers();
        }
    });
}

 
Right, so now that we have an Observable which is going to emit some data, what we need next is to create an Observer that is going to subscribe to that source of data and receive the numbers list. Let’s have a look to a standard Observer:

private Observer getOddNumbersObserver() {
    return new Observer<List<Integer>>() {
        @Override
        public void onCompleted() {
            LogHelper.addLog(mTvLog, "getOddNumbers() - onCompleted()");
        }

        @Override
        public void onError(Throwable e) {
            LogHelper.addLog(mTvLog, "getOddNumbers() - onError()");
        }

        @Override
        public void onNext(List<Integer> integer) {
            LogHelper.addLog(mTvLog, "getOddNumbers() - onNext()" + integer);
        }
    };
}

 
As we can see, the Observer implements three fundamental methods: onNext will be called when the Observable emit an item. onCompleted will be called when the Observable has finished emitting data. And finally onError will be called if there has been any exception or error when emitting data.

We can simplify the Observer in case we just want a single event that will receive the list of numbers and we don’t need to know about the OnComplete and OnError events. To accomplish this we just need to create an Action instead of the Observable, something like this:

private Action<List<Integer>> getOddNumbersAction() {
    return new Action<List<Integer>() {
        @Override
        public void call(List<Integer> integers) {
            LogHelper.addLog(mTvLog, "getOddNumbersAction() - call: " + integers);
        }
    };
}

 
So the last step would be to subscribe this Observer to the Observable, and it would be as simple as this:

    observable.subscribe(observer);

 
And that’s it! When the getOddNumbers() method has finished the calculation of numbers and return, the Observable will dispatch the list of numbers and the Observer will receive the data.
 

Summary

So this has been the introduction and basic operations with RxJava.
You can find all the examples in this public repository.

In next posts we will be looking deeper into more elements of the Reactive extension, like the Operators and Schedulers, etc.

In the mean time please leave here any comments, suggestion or corrections you might find!
 

Tagged ,

A beginners guide to an effective Android testing strategy

Testing quite often is one of the most neglected aspect in many Software projects, and in Android this has been particulary a common issue since the beginning of the platform.
atsl-logo

Even Google didn’t seem to be making big efforts to encourage testing: Documentation was almost nonexistent, the tools and frameworks were confusing or hard to use and there was almost impossible to find an open source project with good testing implementation.

 

Why testing?

Implement a good suite of different type of tests with a good coverage ratio and maintain it requires time and discipline from the dev team. In some cases the member of the team might not be familiar with the testing frameworks or even never have implemented any  type of test. So what are the benefits of this time and resource investment? Here some of the reasons:

  • Testing allows us to check the correctness of the app features. We should never rely on the QA team to find defects in our code. Is a very common practice to implement some feature, test a couple of use cases, send it to the quality team and wait until they find a few bugs for us and then fix it. This is really a bad practice that a professional developer should never do. We should be confident that the deliverables that we release to QA team shoulders been tested throughly, has a good test code coverage and that our quality colleagues should almost never find a bug.
  • Improves the design and modularity of our code base. If we create a new feature with a TDD approach, we will be building our classes in short iterations, thinking in the interface and driving the implementation with the proper user requirements in mind. This will make our modules and classes small, independent and with one only responsibility unit.download
  • Help us to implement new features or refactor existing one with much more confidence that our changes will not break current working and tested
    functionalities. If every time we add a new piece of code to our project we run our test and all pass, we can be sure that we didn’t implement anything that is affecting and having negative side effects on the existing features.

 

Types of test

In the Android platform, generally we will implement two categories of tests: Unit Tests and Integration Tests.

  • Unit Tests.  We will test small and independent pieces of code. It might be a single class, an interface or just a method. We can consider it as the smallest possible testable piece of code part of an specific independent module. In Android we will use JUnit running either locally on the JVM (prefer this one as fastest method) or in an emulator or real device.
  • Integration Tests. We are testing more than one individual module working together that implements a complete functional part of our system. For example we test the Login feature of our application where different entities works together and and we want to test that the login process is accomplished successfully on different scenarios. In this case in Android  we will implement UI Instrumentation tests with Espresso and Automation tests with UI Automator.

 

Architecting the app for testing

As we mentioned before one of the complains of the Android community was that testing the platform was a difficult task. Apart from the lack of a good testing framework, the developers faced the problems of implementing tests for modules (Activities, Fragments, etc) coupled to multiple Android SDK dependencies.

In order to mitigate this issue, one best and most common solutions is to architect our application using the MVP pattern. With this approach we manage to have a clear separation of concerns of our modules making much more easy to unit test our models and use cases classes without having to mock and get around of all the Android SDK dependencies.

Typically we will have our View layer with the Activity or Fragment that have almost no logic at all. A Presenter acting as a bridge and a Model which will have our use cases and where we will probably focus most of our unit tests.

In a previous I made a basic introduction of the MVP pattern where you can see all these concepts with more detail.

Test Pyramid

Following the TestPyramid concept described by Mike Cohn, Unit Tests should be around test_pyramid60-70% of our test code base and the rest 30% should be implemented as End-to-End tests (Integration, functional, UI tests).

The reason for this is that the end to end tests has a few problems, like you need to wait until the app is deployed and running in a device. Then probably the test will have to deal with things like login, registrations, database access, etc.
Also if you find a bug it will be hard to figure out where exactly the problem is, as it could be in any of the multiple modules and components that are involved in the specific user flow.

On the other hand Unit Tests are fast, reliable and they isolate the test scope to very specific and isolated pieces of the system which makes it a much better way to identify the defects in our system.
If we have build our code base using TDD, we will probably have test covered almost all modules of our application which will give us peace of mind that all parts of the application are being tested and any regression would be detected.

Implementing Unit Tests

First let’s add to the project build.gradle file the required dependencies for Espresso, JUnit, UIAutomator, etc.

    // Dependencies for unit testing
    testCompile 'junit:junit:4.12'
    testCompile 'org.mockito:mockito-all:1.10.19'
    testCompile 'org.hamcrest:hamcrest-all:1.3'

    // Android Testing Support Library's runner and rules
    androidTestCompile 'com.android.support.test:runner:0.3'
    androidTestCompile 'com.android.support.test:rules:0.3'

    // Espresso UI Testing
    androidTestCompile 'com.android.support.test.espresso:espresso-core:2.2'
    androidTestCompile 'com.android.support.test.espresso:espresso-intents:2.2'

    // UIAutomator Testing
    androidTestCompile 'com.android.support.test.uiautomator:uiautomator-v18:2.1.1'
    compile 'javax.inject:javax.inject:1'

As we mention before we have two options to run Unit Tests, one is locally on the JVM and the other is running with UI Instrumentation runner. We will favour the local JVM test as they will compile and run much faster. The downside is that these can’t have any Android SDK dependency, but that should be our goal as we saw before using a MVP pattern.
One way to overcome this issue is providing any Android dependency using a mocking framework like for example Mockito.
This will be fine if we just need to mock a couple of dependencies with not many interactions between our code and the SDK, but if we have more complex interactions and we need to spend hours mocking classes, this would be a signal that we should run those test in a emulator or device using Instrumentation Test.

To add the tests in the project we haver will need two folders, one for each type of test as you can see in the picture below, the Unit Test lives in the folder named “test” and the UI test are located in the folder “androidTest”. Both have to be at the same level that our main folder of the project. This is important because otherwise Android Studio will not be able to identify these classes as tests.

Screen Shot 2016-04-02 at 20.14.14

 

Anatomy of a Unit Test

So now we are ready to add a Unit Test, to do this just add a new class to the Test folders of your project and now we will have to specify which runner we want to use, the size type of the test, etc. Let’s have a look at the example below and we will go through the different parts.

@RunWith(MockitoJUnitRunner.class)
@SmallTest
public class EmailValidationTest {

    String EMAIL_REGEX = SignupPresenterImpl.REGEX_EMAIL;

    @Before
    public void setup() {
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void givenValidEmail_RegexCheckReturnsValid() throws Exception {
        String validEmail = &amp;amp;quot;david.guerrero@quoders.com&amp;amp;quot;;
        Assert.assertTrue(validEmail.matches(EMAIL_REGEX));
    }

    @Test
    public void givenInvalidEmail_MissingAt_RegexCheckReturnsError() throws Exception {
        String invalidEmail = &amp;amp;quot;david.guerreroquoders.com&amp;amp;quot;;
        Assert.assertFalse(invalidEmail.matches(EMAIL_REGEX));
    }

    @Test
    public void givenInvalidEmail_MissingHost_RegexCheckReturnsError() throws Exception {
        String invalidEmail = &amp;amp;quot;david.guerrero@quoders&amp;amp;quot;;
        Assert.assertFalse(invalidEmail.matches(EMAIL_REGEX));
    }

    @After
    public void tearDown() throws Exception {
    }
}

@RunWith(MockitoJUnitRunner.class)
We specify the runner we want to use, it might be JUnit runner, the Instrumentation, Automation runner or even a custom runner. It depends on how and where we want to run our test.

@SmallTest
This annotation define the type of test we are runing, where “SmallTest” is usually a Unit Test, a “LargeTest” an end to end UI or Automation test and a “MediumTest” is when we are testing more than one module working together, like an Integration Test. See the table below to compare these different types.
Screen Shot 2016-04-03 at 21.19.34

@Before
The method marked with this annotation will be called every time before a test is launched. It useful to initialise and arrange any data needed for the tests.

@Test
This define a test method. It usually should follow the “Arrange-Act-Assert” pattern:
– Arrange all necessary preconditions and inputs.
– Act on the object or method under test.
– Assert that the expected results have occurred.

@After
This method will be execute after each test and we will use it to release resources, close files, etc.

Running the tests

Finally to run the tests we need to select “Unit Test” on the Build Variant menu. After this we can just right click at the Test package folder and then on “Run Tests..” (or Debug or Run with Coverage).

Screen Shot 2016-04-03 at 21.56.15.png

 

Implementing Integration Tests

As we saw before, these type of test should cover around the rest 30 or 20 percent of our test code base. We will use the Instrumentation and/or Automation frameworks that basically allows us to simulate user interactions on the application that will run in a real device or an emulator.

We are going to use Espresso as our Instrumentation test  framework. With it we can click on buttons, enter texts, do scrolls, etc. See below an example of a Sign Up screen tests.

 

@RunWith(AndroidJUnit4.class)
@LargeTest

public class SingupTest {

    @Rule
    public ActivityTestRule&lt;SignupActivity&gt; mSignupActivityRule = new ActivityTestRule&lt;&gt;(SignupActivity.class);

    @Test
    public void testperformValidCompleteSignup() throws Exception {

        //  Fill up new user fields
        onView(withId(R.id.editTextCreateUserName)).perform(typeText(&quot;david_&quot; + System.currentTimeMillis()));
        onView(withId(R.id.editTextCreateEmail)).perform(typeText(&quot;david.guerrero@quoders.com_&quot; + + System.currentTimeMillis()));
        onView(withId(R.id.editTextCreatePassword)).perform(typeText(&quot;password&quot;));
        onView(withId(R.id.editTextPasswordConfirm)).perform(typeText(&quot;password&quot;));

        //  Click on Sign Up button
        onView(withId(R.id.editTextPasswordConfirm)).perform(click());

        //  Check progress dialog is showed
        onView(withText(R.string.signup_progress)).check(matches(isDisplayed()));

        //  Assert Home screen has been launched
        onView(withText(R.string.title_activity_home)).check(matches(isDisplayed()));
    }
}

As we can see in the example, we are introducing all the fields needed to perform a new user registration, then clicking on the Sign Up button and assert that the Home Activity is launched correctly after this.
Notice how we have marked the test with the “LargeTest” annotation and we are running it with the “AndroidJUnit4” runner.
To run this test we now need to change to Build Variant to the “Android Instrumentation Test” option and then we just need to choose where to deploy and run the app and the test, either in a real or emulated device.

Summary

So that was a quite brief introduction to a much more complex subject as the testing strategy in Android. There are much more to talk about testing but that will be probably part of further posts.

You can find these examples on my work in progress open source project Treepolis in Github.

As usual please leave any comments, suggestion or corrections. What’s your testing strategy?

Tagged , ,

An introduction to MVVM pattern on Android with the Data Binding Library

In a previous post we made a brief introduction to the MVP architectural pattern, describing how it help us to create a much cleaner, testable and modular source code for our application.

In this post we are going to talk about the MVVM pattern and explain how using the new Android Data Binding Library we can achieve the same level of modularity and separation of concerns but one step ahead, making the data binding with the UI layer less verbose and straightforward, which will produce source code less prone to errors and bugs.

 

What is MVVM?

Model-View-ViewModel is a variation of the MVC and MVP patterns initially described and implemented by Microsoft to be used on the .NET platform, specifically with WPF and Silverlight technologies that makes use of the XAML language to implement User Interfaces.

In the Microsoft ecosystem one of the main advantages of this pattern is that the designers can implement the View working completely independent of developers using Blend, which is an amazing UI IDE. Then developers can focus only on the ViewModel and Model and wiring everything with the Binding functionality. This in Android is much more difficult as the UI designer tools are not powerful enough.

Screen Shot 2015-12-05 at 10.59.55

Like in the MVP pattern we separate and architect our code in three well defined layers.

The View defines the pure user interface and it has no logic at all except any related only to the UI. If we focus on the Android platform in this layer we would have Activities, Fragments, Dialogs, Views, etc. As we saw in the MVP post these entities will implement an interface that will be use as bridge with the ViewModel layer.

The Model integrates our data strategy, backend support, pojos, and generally speaking what we all know as business logic. These will be implemented via Interactors which defines uses cases of the domain logic.

And finally we have the ViewModel which differentiate this patterns from others. Conceptually this layer is in charge of the same logic as the Presenter in the MVP, which is acting as a facade and brain between our data model and the user interface.

It will be able to identify the application status and display or fetch data and information using the View and the Model. The ViewModel knows how and where to display the information in the user interface. Also it knows where  and how to get this information from the Model.

But the main difference is how this data are passed from the model to the View, which in the VM happen using a mechanism called Data Binding.

 

What is Data Binding?

Data Binding is a mechanism where a view component is linked to a data entity of the ViewModel without having to implement specific code to transform or assign this data to the visual component. We can send and receive commands and events and also connect data source to the component. In Android this magic happen thanks to the recently added Data Binding Library.

As we can see, one of the main advantages of using Data Binding is the time we save due the amount of code that we don’t have to implement to connect the data and the view and hence the possible bugs and code defects that we will avoid.

 

Implementing Data Binding on Android

First thing we need to use the Android Plugin for Gradle version 1.5.0-alpha1 or higher.

classpath 'com.android.tools.build:gradle:1.5.0'

Then we configure the app to use the data binding feature in the build.grade file.

dataBinding {
enabled = true
}

Now we need to add the data binding to the component that is going to display the data that we need. For this example we will use two TextView which are going to display a user name and email that we will fetch from a web service using Retrofit. Once we have the response from the server, this info will be automatically updated on the view.

So let’s add the binding code in the layout of our view, in this case we are adding a reference to the pojo class that contains the data that we are binding and that will fill up with the response of our server request. Also we are setting the TextView wit the field of the that contains the specific user name and email:

&amp;amp;lt;layout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" tools:context="com.quoders.apps.androidbootstrap.mvvm.MvvmExampleFragment"&amp;amp;gt;

&amp;amp;lt;data&amp;amp;gt;
&amp;amp;lt;variable name="commentItem" type="com.quoders.apps.androidbootstrap.rest.model.CommentItem"/&amp;amp;gt;
&amp;amp;lt;/data&amp;amp;gt;

&amp;amp;lt;TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="@{commentItem.name}" android:layout_marginTop="15dp"/&amp;amp;gt;

&amp;amp;lt;TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="@{commentItem.email}" android:layout_marginTop="5dp"/&amp;amp;gt;
&amp;amp;lt;/layout&amp;amp;gt;

Next we need to initialise the binding objet in the Activity or Fragment. Note that the FragmentMvvmExampleBinding is created automatically by Android Studio:


FragmentMvvmExampleBinding mBinding = DataBindingUtil.setContentView(getActivity(), R.layout.fragment_mvvm_example);

And finally when we have the response from the HTTP request we do the binding with the pojo that contains the data to bind:


mBinding.setCommentItem(mComentItem);

As you can see in this example, the UI component is update on demand when we have the server response data. Although this feature is pretty cool, what makes data binding really powerful is the ability to update the UI component automatically each time that the status of the bind object changes. We accomplish this extending our pojo data class from the BaseObservable class that the Data Binding library provides and setting the fields as observables. In our example it would look  like this:

public class CommentItem extends BaseObservable {

@Expose
private String name;
@Expose
private String email;

@Bindable
public String getName() {
return name;
}

@Bindable
public String getEmail() {
return email;
}
}

There are multiple possibilities like binding collections, resources, automatic setters, etc… But all this due its extension will be the topic of another post!

You can find the source code with this example here in the FragmentMvvmExample. To check out how to implement the division of layers on MVP / MVVM have a look to my previous post.

As usual all comments, suggestions or critics are more than welcome, please leave your comments!

 

Tagged , , ,

A brief introduction to a cleaner Android architecture: The MVP pattern

As the Android platform has been maturing, developers found that the standard approach to organise the architecture and design of the application code wasn’t the best at all. Usually we ended up having a massive monolithic module, an Activity or a Fragment, containing business and UI logic, creating an unmaintainable and untestable messy project.

Google itself haven’t provided so far a good practice guideline or code examples showing a modular and decoupled approach that implements any of the well known and widely used design patterns, like for example MVC which is encouraged by default on the iOS platform or the common MVVM in Microsoft environments.

One of the most common pattern that the community of Android developers has been using for a while and that has got lot of attention is the Model View Presenter (MVP) pattern and we will focus on it on this post. We will not go through a deep academic description of the pattern but we will focus on the advantages and practical use of it. For an awesome analysis of the MVP and other patterns take a look at this classic post from Martin Fowler about GUI architecture.

So what’s MVP?

18289

Basically MVP is an architectural design pattern that divides our application code in three entities in order to achieve a modular design, implementing the separation of concerns concept, allows an easier implementation of unit tests and making possible to reuse and replace modules either of our UI, data or business layer.

MVP is an evolution of MVC and it has multiple variants and implementations. There has been a lot of conversations and debate about the best and proper way to adopt it on Android. I’m going to expone my way which I have been using in a couple of projects and I reckon works better for me. Of course it doesn’t mean is the best or only one that works on Android, so please leave any comment and suggestions if you find any area of improvement.

Ok so let’s see who is who in this approach.

The View

This entity is going to include the visual part of our app, it is only the UI and it will not have any logic or knowledge of the data displayed. The View doesn’t know anything about the business logic or how to get the data it has to show to the user.

Activities, Fragments, Dialogs, etc… would be included in this category. This elements will contain only initialisation and display functionalities of the visual components and elements to display information to the user. It will not contain any functional or business logic like access to database or web server for example.

This module (Activity, Fragment, etc) exports an interface that will be used by the Presenter, which is responsible and have the knowledge and logic about how, when and what to show in the View. This interface will have methods like “showProgressBar”, “showLoginErrorMessage” or “launchSignupActivity”. Here is an example:

public interface WelcomeView {

    void launchHomeActivity();
    void LaunchSignupActivity();
    void closeActivity();

    void setWrongUsernameError();
    void setWrongPasswordError();

    void showLoginErrorAlertDialog();
}

The Presenter

As we mentioned before, this entity is going to have all the logic and knowledge about what, how and when to display in the user interface. It will be responsible of capture events raised by the user when interacting with the UI and perform any action.

The presenter also acts as a bridge between the View and the Model fetching any data needed from the data layer, making any transformation and display this info to the user on the View.
This entity ideally shouldn’t have any dependency of the Android SDK such us Context or Activity references.

The Activity will have a reference to the Presenter interface and it will use it to communicate any event occurred on the View, like the user tap on a button or the user enter any data in a TextView and then it will decide what to do in reaction of that event.

Here is an example of a Presenter interface:

public interface WelcomePresenter {
    void onCreateAccountClick();
    void onActivityResultCalled(int requestCode, int result);
    void onLoginClick();
}

So for example let’s say that if the user tap on a Logout button, the View call the exported method “onLogoutClick” of the Presenter interface. Then the it knows what interactor of the Model layer needs to invoke to perform a Logout action on the app.

Once the log out success callback has been received, the Presenter will perform any action on the View, for example closing the Activity and displaying a home screen Activity.

The Model

In this entity we will include the “interactors” (use cases of our business logic) that will perform and manage any business layer logic and data access, like fetching data from our web service, accessing the database, etc.

Once we have that piece of data the interactor will send it back to the Presenter and this will decide what to do with this data and how to show it to the View as we saw in the previous point.

Here an example of an implementation of an interactor:

public class WelcomeInteractorImpl implements WelcomeInteractor {

    private WelcomeInteractorListener   mListener;

    public WelcomeInteractorImpl(WelcomeInteractorListener listener) {
        this.mListener = listener;
    }

    @Override
    public void loginWithUserName(String username, String password) {

        ParseUser.logInInBackground(username, password, new LogInCallback() {
            public void done(ParseUser user, ParseException e) {
                if (mListener != null) {
                    if (user != null) {
                        mListener.onLoginSuccessful();
                    }
                    else {
                        mListener.onLoginError(e);
                    }
                }
            }
        });
    }
}

Summary

So this is a very brief summary of what is MVP and how to use it on Android to achieve a cleaner, modular and testable source code. This is just an interpretation of the pattern and is not a silver bullet or the perfect solution for our apps, so any comments or critics are more than welcome!

To see an example of this implementation you can take a look to one of my open source experimental apps “Treepolis”. Is still an in progress project and you can find it here in Github
To see a practical example of the pattern used for the Welcome screen and login functionality check this folder.

Tagged , , ,

Share your Android and iOS application with Google App Invites API

One of the most common features that we usually implement in our apps is the ability of the user to share the app with friends.
This is a great way to make our app grow and a free mechanism of user acquisition.

Normally we have implemented this functionality with some kind of custom message and allowing the user to send it by email, text message, etc.

app-invites

Now we can achieve this with a much better user experience and customisable way using the new Google App Invites Beta API that was announced in the last Google I/O 2015.

With App Invites we not only can share the app but also send deep links, customised invite cards, link with Google Analytics to track the flow, etc.

Integrating the API

So lets start to set up our project adding the Google Play Services metadata in the app manifest:

<meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version" />

Then we need to add the dependency to our top-level build.gradle:

classpath 'com.google.gms:google-services:1.3.0-beta1'

and also apply the gsm plugin to our app-level build.gradle:

apply plugin: 'com.google.gms.google-services'

Finally we add the Google Play Services dependency in the app’s Gradle file:

compile 'com.google.android.gms:play-services:7.5.+'

Right, next thing we need to add to our project is a Json configuration file that we will get from Google that provides service information specific to our app.
To do this we will have to add in the Google Developer Console our application package name and the SHA1 key from our key store. Click here to access the dev portal to do so.

Once we have the configuration google-services.json file we just need to copy it into the app/ or mobile/ directory of our project.

Sending an app invite

Ok, so now that we have finished the integration let’s do the funny part, and send an app invitation.
To achieve this we just need to build and start an Intent, something like this:

    Intent intent = new AppInviteInvitation.IntentBuilder("Try this app!")
            .setMessage("Hey take a look to this awesome app that I'm using!")
            .build();
    startActivityForResult(intent, REQUEST_INVITE);

If everything went well, when we launch our app and we launch this intent we should see a really nice interface that will show the user’s contacts list and the option to send the invite.

When the destination user receives the invite, depending on if he or she has installed the app different things might happens as we can see in the diagram below:

ai-flow

So that’s it! This is just an introduction but there are more interesting options to explore as the integration with Google Analytics, deep links features, etc.

You can find an example of the integration and use for Android in my examples project here. And as usual any comments and feedback are more than welcome!

Tagged , , ,

Introduction to Android HTTP communication with Retrofit

In a previous post I described how to implement HTTP requests using the Google’s library Volley. We saw how to save lot of boilerplate code in such a critical part of our apps like the networking communication with our server using a well tested and reliable library.

We showed how straightforward is to have so useful features like parallel HTTP requests, cancel petitions, image downloads caching, etc.

But Volley is not our only option, there are more libraries out there that does a really good job,  and one of the well known and widely used is Retrofit from the Square people.  In this post you can find a very good comparison  between the two libraries where Retrofit would win as it is faster that Volley, but you better try and test by yourself and check which one would fit better on your project.

You can find here in my AndroidBootstrap project in Github how to integrate the library in an Android Studio project and a few examples of use.

 

Integration in our project

You can download the library .jar from here or if you’re using Maven:

<dependency>
 <groupId>com.squareup.okhttp</groupId>
 <artifactId>okhttp</artifactId>
 <version>2.0.0</version>
</dependency>
<dependency>
 <groupId>com.squareup.okhttp</groupId>
 <artifactId>okhttp-urlconnection</artifactId>
 <version>2.0.0</version>
</dependency>

Or if using Gradle:

compile 'com.squareup.retrofit:retrofit:1.9.0'

 

Retrofit client

The first thing we need to do is to initialise the Retrofit rest client object. You might want to use a singleton to manage the life cycle of the client if you’re planning to do frequent request on your app:

public class RestClient {

    private static final String API_URL = "http://jsonplaceholder.typicode.com";

    private static RestApi mRestApi = null;

    public static synchronized RestApi getInstance() {

        if(mRestApi == null) {

            RestAdapter adapter = new RestAdapter.Builder()
                    .setEndpoint(API_URL)
                    .build();

            mRestApi = adapter.create(RestApi.class);
        }

        return mRestApi;
    }
}

 

A simple HTTP GET request

Retrofit uses Java interfaces and annotations to define the REST API requests. Then it will generate the necessary code thto perform the HTTP requests and finally will convert the Json response in the specific pojo object using Gson.

Let’s take a look to this example:

@GET("/comments")
void getCommentsAsync(@Query("postId") String postNumber, Callback<list> callback);

As you can see “@GET” specifies the type of request and “/comments” is the path of the request.

Then we have the “@Query” annotation that specifies the addition of a param to the url which will take the value of the param “postNumber”.

Finally we can see the Callback parameter where retrofit will retrieve the object that has been created from the Json response using the Gson library.

In case we need to do a synchronous request the interface will look like this:

@GET("/comments")
List getCommentsSync(@Query("postId") String postNumber);

If we need to perform a POST operation:

@POST("/comments")
void postComment(@Body CommentItem item, Callback cb);

And if we need to add headers to our request:

@Headers("Cache-Control: max-age=640000")
@GET("/comments")
List getCommentsWithCustomHeader();

 

So this is a very brief introduction to the Retrofit library. As mentioned before you can find examples of the use and integration in my Bootstrap Android project. I’ll be adding more examples of useful libraries or snippets in the future.

And finally if you have any comment or suggestion please don’t hesitate in leave it below!

Tagged , , ,

HTTP networking on Android using Volley

One of the most common functionalities that as Android developers we need to implement is the network communication. Almost all apps at some point needs to get some kind of data from a server, web service, etc.

We could implement our own classes using for example the Java HttpURLConnection, but as pragmatic, productive and lazy developers we should always try to don’t reinvent the wheel and find some reliable and well tested library.

Two of the best and more used options are Retrofit from the Square people and Volley from Google, which I’m going to focus in this post and I will leave Retrofit for another post.

 

What is Volley?

Volley is a library created by Google that offers out of the box a set of very cool features, amongst others :

  • Concurrent connections.
  • Automatic requests scheduling and cancelation.
  • Memory and disk response caching.

Here you can find a good talk at the 2013 Google I/O conference from Ficus Kirkpatrick:

 

Integration in our project

So, let’s see how to use it. First thing we have to clone the project from Git:
https://android.googlesource.com/platform/frameworks/volley

and then import it in our project or make a .jar and include it as a library.

Probably our app will be making requests in different activities quite often so the most optimum way to manage the life of our Volley object is implementing a Singleton class and create the instance it on the Application class instead or creating a new object on each activity. This singleton is going to contain the RequestQueue object that will manage the requests concurrency. Something like this:

    private static VolleyManager mInstance = null;
    private static Context mContext;
    private RequestQueue mRequestQueue;

    private VolleyManager(Context context) {
        mContext = context;
        mRequestQueue = getRequestQueue();
    }

    public static synchronized VolleyManager getInstance(Context context) {
        if (mInstance == null) {
            mInstance = new VolleyManager(context);
        }
        return mInstance;
    }

    public RequestQueue getRequestQueue() {
        if (mRequestQueue == null) {
            // getApplicationContext() is key, it keeps you from leaking the
            // Activity or BroadcastReceiver if someone passes one in.
            mRequestQueue = Volley.newRequestQueue(mContext.getApplicationContext());
        }
        return mRequestQueue;
    }

    public <T> void addToRequestQueue(Request<T> req) {
        getRequestQueue().add(req);
    }

 

HTTP GET

Now we are going to implement a simple HTTP GET request that will retrieve a Json object. Volley offers four types of requests responses: “StringRequest”, “ImageRequest”, “JsonObjectRequest” and finally the ability to implement our custom request.

In this example we will be using a JsonObjectRequest. It’s based on real code from our public transport app BilbaoMoves, where we are calling to our server to get the real time arrivals of a specific transport stop. I just changed the endpoint url and the classes names.

It looks like this:

	JsonObjectRequest jsObjRequest =
        new JsonObjectRequest(Request.Method.GET, "http://urlToAnAwesomeEndpoint/webservice/",
                null, new Response.Listener<JSONObject>() {

            @Override
            public void onResponse(JSONObject jsonObject) {

				Gson gson = new Gson();

                MyExampleClass myExample =
                    gson.fromJson(jsonObject.toString(), MyExampleClass.class);

				//	Do something awesome here with myExample object
				//	.......

           }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {

            	//	The request failed  😦
            }
        });

        // Access the RequestQueue through the singleton class.
        mVolleyMng.addToRequestQueue(jsObjRequest);

 

HTTP POST

Creating a HTTP POST and send parameters in the request is quite straightforward as you can see in this example:

ExampleClass exampleObj = new ExampleClass();
exampleObj.setName("David");
exampleObj.setSurname("Guerrero");

JsonObjectRequest req = new JsonObjectRequest(URL, new JSONObject(exampleObj),
     new Response.Listener<JSONObject>() {
         @Override
         public void onResponse(JSONObject response) {
             try {
                  //   Everything went OK
             } catch (JSONException e) {
                 e.printStackTrace();
             }
         }
     }, new Response.ErrorListener() {
         @Override
         public void onErrorResponse(VolleyError error) {
              //   Hmmm... Something went wrong
         }
 });

// add the request object to the queue to be executed
ApplicationController.getInstance().addToRequestQueue(req);

</pre>
<pre>

 

Cancel a Request

Sometimes we will need to cancel a request, for example when the user close the app or change to a different activity where we don’t need any more the data provided by the request. We could place the cancel request code in the onStop event of our activity, something like this:


@Override
protected void onStop () {
    super.onStop();
    if (mRequestQueue != null) {
        mRequestQueue.cancelAll(TAG);
    }
}

 

And that’s all. This is a basic introduction to how to make basic requests, but Volley offer another really interesting and useful features like caching and image loader (eg. to populate a list view with images asynchronously), but that will be material for another post. Until then, please all comments, suggestions and questions are very welcome!

 

Tagged , ,

Source Code Version Control for Android with Eclipse and EGit (I)

In this post I’m going to explain how to install and configure the EGit plugin for Eclipse and how to clone an existing project from a Git repository in a web based hosting service, in my case Assembla.

We assume that you already have a hosting service account and that you’ve uploaded your public key file and that there is a project to clone.

So let’s start step by step. First of all, open Eclipse and go to “Help/Install New Software…” and type “http://download.eclipse.org/releases/indigo/&#8221; in the text box to the right of “Work with:” text.

Press Add and then you will see a list of categories of installable software. Inside Collaboration category press Eclipse EGit and the Next, Next, and Finish.

After restart Eclipse, copy the git URI that you hosting service tells you for the project, it should look something like this: “git@git.assembla.com:PROJECTNAME.git”. In this case is “assembla” but it’s depends on your hosting name.

Now open up a new perspective of the “Git Repository Exploring” and press the button “Clone a Git repository”. It should already get the URI from your clipboard and fill everything out for you, so just press Next, Next, and Finish and…  Voila!  You have downloaded your project.

Now we have to import the downloaded project to our workspace in order to start to work with it. So just go to Eclipse “File/Import…”, now select “Git/Projects from Git” and press Next. You’ll see the downloaded folder, press Next and now choose “Import existing project” and select the project that you want to import then Next and Finish.

And that’s it!  If everything went well you have your project ready for compile and have fun!

To Commit, just right-click your project and select Team/Commit.

For pushing to your remote repository, go Team/Push and set it up when doing this the first time – Click next on the first screen, nothing to see here. On the next screen, choose “master ” and “Add spec” next to it. Close it off with next and then finish.

And that’s all. I hope that you find it useful and if you have any doubt don’t hesitate to contact me.

Tagged , ,