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.

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:

DataModel

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.

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:

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 🙂

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!

Android Architecture Components

Android Architecture Components

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 ORM between 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.

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:

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

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 ViewModel outlives 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.

Let me know what your thoughts are on the comment section below.

Happy Coding!

Dagger 2 Made Simple In Android – Part 1

Dagger 2 Made Simple In Android – Part 1

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:

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

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 :

  1. Scope
  2. Module
  3. 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.

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.

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 🙂

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!

How To Debug Your Android App over WiFi

How To Debug Your Android App over WiFi

Hello guys, its been a while since I wrote an article about code here. I have been pre – occupied at my new workplace, but still, there are more things to come. Keep subscribing 🙂

Now, I wanted to write about wireless debugging in Android. Its a little trick I discovered a while ago and it was immensely helpful. So far, whenever I was working on my Android apps, I had to connect it to my laptop with a USB cable. The USB cable is annoying and limits my movements. Then after some digging, I found out this easy work around.

All you need is a USB cable (for the initial setup) and have both devices in the same network. The screenshots in the following section are from my MacBook Pro, but it works on any operating system.

Steps

You need to connect your device to your computer via USB cable. Make sure USB debugging is working. You can check if it shows up when running adb devices.

Run adb tcpip 5555

Disconnect your device (remove the USB cable).

Go to the Settings -> About phone -> Status to view the IP address of your phone.

Run adb connect <IP address of your device>:5555

If you run adb devices again, you should see your device.

Now you can execute adb commands or use your favorite IDE (Android Studio) for android development – wireless!

Now you might ask, what do I have to do when I move into a different work space and change WiFi networks? You do not have to repeat steps 1 to 3 (these set your phone into WiFi-debug mode). You do have to connect to your phone again by executing steps 4 to 6.

Unfortunately, the android phones lose the WiFi-debug mode when restarting. Thus, if your battery died, you have to start over. Otherwise, if you keep an eye on your battery and do not restart your phone, you can live without a cable for weeks!

Happy Wireless Coding!