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.

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.

Prerequisites

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.

.travis.yml

YAML

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

language: android

sudo: required

jdk: oraclejdk8

env:

global:

-ANROID_API_LEVEL="your api level"

-ANDROID_BUILD_TOOLS_VERSION="your build tools version"

android:

components:

-tools

-platform-tools

-build-tools-$ANDROID_BUILD_TOOLS_VERSION

-android-$ANDROID_API_LEVEL

-extra-google-google_play_services

-extra-google-m2repository

-addon-google_apis-google-$ANDROID_API_LEVEL

licences:

-'android-sdk-preview-license-.+'

-'android-sdk-license-.+'

-'google-gdk-license-.+'

before_script:

-mkdir-p"$ANDROID_HOME/licenses"

-cp./licenses/*"$ANDROID_HOME/licenses"

before_cache:

-rm-f$HOME/.gradle/caches/modules-2/modules-2.lock

-rm-fr$HOME/.gradle/caches/*/plugin-resolution/

cache:

directories:

-$HOME/.gradle/caches/

-$HOME/.gradle/wrapper/

-$HOME/.android/build-cache

script:

-./gradlewbuildcheck

before_install:

-chmod+xgradlew

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.

Bonus

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.

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:

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.

ViewModel

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.

View

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.

DataModel

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.

ViewModel

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:

1

2

3

4

5

6

7

8

9

10

11

publicclassViewModel{

privatefinalIDataModel mDataModel;

publicViewModel(IDataModel dataModel){

mDataModel=dataModel;

}

publicObservable<Data>getSomeData(){

returnmDataModel.getSomeData();

}

}

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.

View

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!!!

Conclusion

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 🙂

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:

1

2

3

4

5

6

7

<LinearLayout

xmlns:android="http://schemas.android.com/apk/res/android"

xmlns:tools="http://schemas.android.com/tools"

...

>

...

</LinearLayout>

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:

1

2

3

4

5

6

<TextView

android:layout_width="match_parent"

android:layout_height="wrap_content"

...

tools:text="Test test, let's add some really really really long text"

/>

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:

1

2

3

4

5

6

<ListView

android:id="@+id/list_books"

android:layout_width="match_parent"

android:layout_height="match_parent"

tools:listitem="@layout/list_item"

/>

2. RecyclerView

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

1

2

3

4

5

6

7

<android.support.v7.widget.RecyclerView

android:id="@+id/recycler_books"

android:layout_width="match_parent"

android:layout_height="match_parent"

tools:listitem="@layout/list_item"

android:scrollbars="vertical"

tools:scrollbars="none"/>

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:

1

2

3

4

5

6

7

<TextView

android:layout_width="match_parent"

android:layout_height="wrap_content"

...

android:text="@string/welcome_text"

tools:text="Test Test, add some really really really long text"

/>

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

During the Google I/O 2017, there were a lot of new announcements for the Android Platform. One of the announcements was the new architecture guidelines for Android! This is a welcome addition to the Android platform. They reduce the amount of boilerplate and repetitive code, leaving you to focus on the core functionality of your application. These components can be used in isolation but work really well when used together.

Now, I know this might not be new to many of us who have been doing Android for a while now. But nonetheless, I decided to visit this area and write a simple and detailed article about them.

Now, we will look at these three components.

Room

LiveData

ViewModel

Room

I have already written some articles about Room, you can go through them to understand it better. But let me shed some light here also. Room is a new way to create databases in your Android apps. Room eliminates a lot of the boilerplate code you had to write previously to store data in your apps. Room is an ORMbetween Java classes and SQLite. With Room, you no longer need to use Cursors and Loaders.

LiveData

LiveData allows you to observe changes to data across multiple components of your app without creating explicit, and rigid dependency paths between them. When you combine LiveData with Room, it gives you the ability to receive automatic database updates which can be difficult to achieve by just using a standard SQLiteDatabase.

1

2

3

4

5

6

eventDao=eventDatabase.eventDao();

eventDao.getEvents().observe(this,events->{

Log.d(TAG,"Events Changed:"+events);

adapter.setItems(events);

});

LiveData is lifecycle-aware, meaning it respects the lifecycle of other app components, such as activities, fragments, or services. This awareness ensures LiveData only updates app component observers that are in an active lifecycle state.

The advantages of using LiveData

Using LiveData provides the following advantages:

Ensures your UI matches your data state

LiveData follows the observer pattern. LiveData notifies Observer objects when the lifecycle state changes. You can consolidate your code to update the UI in these Observer objects. Instead of updating the UI every time the app data changes, your observer can update the UI every time there’s a change.

No memory leaks

Observers are bound to Lifecycle objects and clean up after themselves when their associated lifecycle is destroyed.

No crashes due to stopped activities

If the observer’s lifecycle is inactive, such as in the case of an activity in the back stack, then it doesn’t receive any LiveData events.

No more manual lifecycle handling

UI components just observe relevant data and don’t stop or resume observation. LiveData automatically manages all of this since it’s aware of the relevant lifecycle status changes while observing.

Always up to date data

If a lifecycle becomes inactive, it receives the latest data upon becoming active again. For example, an activity that was in the background receives the latest data right after it returns to the foreground.

Proper configuration changes

If an activity or fragment is recreated due to a configuration change, like device rotation, it immediately receives the latest available data.

Sharing resources

You can extend a LiveData object using the singleton pattern to wrap system services so that they can be shared in your app. The LiveDataobject connects to the system service once, and then any observer that needs the resource can just watch the LiveData object.

ViewModel

A ViewModel is not a new concept, nor is it neccesarily an Android concept. The name ViewModel came from the MVVM pattern designed by Microsoft in around 2005. With the new Architecture Components, one of the new classes is the ViewModel class.

ViewModels are responsible for preparing data for the View. They expose data to any view that is listening for changes.

For example, if you need to display a list of users in your app, make sure to assign responsibility to acquire and keep the list of users to a ViewModel, instead of an activity or fragment, as illustrated by the following sample code:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

publicclassMyViewModelextendsViewModel{

privateMutableLiveData<List<User>>users;

publicLiveData<List<User>>getUsers(){

if(users==null){

users=newMutableLiveData<List<Users>>();

loadUsers();

}

returnusers;

}

privatevoidloadUsers(){

// Do an asyncronous operation to fetch users.

}

}

You can then access the list from an activity as follows:

1

2

3

4

5

6

7

8

9

10

11

publicclassMyActivityextendsAppCompatActivity{

publicvoidonCreate(Bundle savedInstanceState){

// Create a ViewModel the first time the system calls an activity's onCreate() method.

// Re-created activities receive the same MyViewModel instance created by the first activity.

MyViewModel model=ViewModelProviders.of(this).get(MyViewModel.class);

model.getUsers().observe(this,users->{

// update UI

});

}

}

The ViewModel class in Android has some specific facts you should keep in mind when using it:

A ViewModel can retain its state across Activity configuration changes. The data it holds is immediately available to the next Activity instance without needing to save data in onSaveInstanceState() and restore it manually.

A ViewModeloutlives the specific Activity or Fragment instances.

A ViewModel allows easy sharing of data across Fragments (meaning you no longer need to coordinate actions via an activity).

A ViewModel will stay in memory until the Lifecycle it’s scoped to goes away permanently – in the case of an Activity, once it finishes; in the case of a Fragment, once it’s detached.

Since a ViewModel outlives the Activity or Fragment instances, it shouldn’t reference any Views directly inside of it or hold reference to a context. This can cause memory leaks.

If the ViewModel needs an Application context (e.g. to find a system service), it can extend the AndroidViewModel class and have a constructor that receives the Application in the constructor.

In Summary

The new Android Architecture Components address common scenarios that we haven’t been able to handle easily before, reducing the amount of boilerplate and repetitive code, leaving you to focus on the core functionality of your application. In the next couple of days, I will prepare an article about the MVVM Architecture in Android using the Architecture Components and Dagger 2.

Howdy guys, I have decided to give you my perspective on Dagger 2 and its implementation using the simplest words possible and avoiding all the jargon. This will be a short series about Dagger, remember to follow the next articles 🙂

What is DI?

Dependency injection is a very simple and common practise that we do everyday without realizing it. But when the big term (Dependency Injection) is used, is appears as though it’s a monster we’ve never heard of.

In simple terms, DI means supplying an Object whatever it is that it needs to do its job. For example:

The Person Object here requires a String (name) in order to do its job

Java

1

2

3

4

5

6

7

8

publicclassPerson{

Stringname;

publicPerson(Stringname){

this.name=name;

}

}

Our object Person will require String (name) in order to do its job. Let’s use DI to solve this.

1

2

3

4

5

6

publicclassMyName{

privatevoidcreateAPersonObject(){

Person person=newPerson("MyName");

}

}

Voila! We’ve just performed DI. We’ve satisfied Person’s object dependency by giving it what it needs. This is awesome. We have one problem though, we have given Person object the responsibility of creating its own dependencies, that is bad practice.

So, how do we solve this?

Somebody call Dagger!!!

Diving into Dagger 2

Dagger helps solve this problem by creating the dependencies for us after which we just pass them to our objects, hence reducing their work and make them focus on their real tasks.

Dagger has 3 building blocks :

Scope

Module

Component

Scope

Well, scope is just scope, or in other words, the boundary in which the instances or dependencies created by Dagger will cover. We can have an Application Scope for dependencies that last throughout the application lifecycle, or we can have Activity Scope and even Fragment Scope as well, depending on your needs.

Most people like to use the @Singleton annotation for dependencies that last throughout the Application Scope, but it is recommended to create your own scope (there’s a reason). This is how you can create a scope.

1

2

3

4

5

@Scope

@Documented

@Retention(RetentionPolicy.CLASS)

public@interfaceApplicationScope{

}

Module

This is the guy who will provide or give us all our dependencies. But since dagger is not magic, we have to tell it how to create those dependencies. Let’s take a look.

As you can see, a module requires a couple of things. First, you should annotate it @module for Dagger to know that this is a module. Second, it needs an @scope annotation for it to know the scope of the dependency and lastly an @provides annotation for every method/function that will provide a dependency.

Inside these methods is where you tell Dagger how to create your dependencies.

Component

This is now the link between our dependencies(from the module) and Dagger itself.

1

2

3

4

5

6

@ApplicationScope

@Component(modules={AppModule.class})

publicinterfaceBaseComponent{

Context exposeContext();

Retrofit exposeRetrofit();

}

It also requires some few things. First, the scope and in this case we want our dependencies to last throughout the app’s lifecycle hence we use @ApplicationScope. Second, it requires an @Component annotation to tell Dagger that this is a component.

Inside the @Component annotation, you give it your Module Class(es). Lastly, expose the dependencies that you will need to access from other parts of the application.

Final Steps

Finally, you will need to build your project in order for Dagger to generate the classes it needs to do the job 🙂

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

publicclassMyApplicationextendsApplication{

staticBaseComponent mBaseComponent;

@Override

publicvoidonCreate(){

super.onCreate();

mBaseComponent=DaggerBaseComponent.builder()

.appModule(newAppModule(this))

.build();

}

publicstaticBaseComponent getComponent(){

returnmBaseComponent;

}

}

As you can see Dagger generates a class for your component with the name Dagger in front of your component name. Since dagger uses builder pattern, you can chain methods on it to create your module and then satisfy its dependency (our module depends on context) by passing this, which is an application context in this case.

Summary

There you go folks! That is Dagger in a nutshell. Next we will talk about some common Dagger errors and how to solve them, then dig deep into more complex Dagger implementations than this. So stay tuned!

If you found this helpful, please share (Blessed are those who share!).

Remember to leave your opinions, remarks, questions or a comment and I will be glad to answer and help where I can. Thanks for your time, appreciated. Cheers!!!

Happy Coding!

Posts navigation

About Me

Hello I am Juma Allan, Founder and Author of Android Study. I am currently working as the Lead Android Engineer at dLight Solar, an Open Source Enthusiast and a big time Android Lover, learning Go and sharing my knowledge with others.

“If you don’t build your dream someone will hire you to help build theirs”