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.

Building for scale at d.light Solar, our Android Journey : Modularization [Part 2]

Building for scale at d.light Solar, our Android Journey : Modularization [Part 2]

Single module android applications will most likely do the job and there’s nothing wrong with that at all. But in cases where our applications may grow, modularizing our applications can help us to achieve many things.

Modularization helps the app scale – builds are faster, tests are faster, and it’s easier to understand how the app works. If the app is modularized in a logical way, then individual modules will be the responsibility of a particular team, and when working on a feature, only a few modules would be affected, maybe even only one. This impacts how effectively developers can work on the app. For example, developers no longer have to build the entire app when they make a change.

Furthermore, it helps conceptually group related code in the app, making the app easier to understand. In essence, instead of needing to deal with problems at the scale of the entire app, you can now spend most of your time only considering a small amount of the codebase, which will become increasingly valuable as the app scales. A good feature module should be whatever structure the feature teams find to be beneficial.

Modules will hold features or logical pieces of features, and these are likely to vary greatly in size (although a one class module is probably too small). However, we want to have modules be the smallest self-contained unit of functionality that a person is likely to work on at a given time. That way, a developer sees the highest benefit: they see the smallest possible build time and test time for the amount of code they’re working on.

Another consideration is that you want to avoid having dependencies between your feature modules. Dependencies mean that if you change one feature module, other modules have to be built or tested. While dependencies can be eliminated using the base class trick, it’s something you want to keep to a minimum – it somewhat obscures how the code works and adds an invisible dependency that might come back to haunt you later (for instance, if you run tests based on what modules appear to have changed).

The Application Module

This is essentially the main module of your application and will often be under the app module. It’s likely a module that you’ve already encountered or used at some point during your development career.  It’s usually under the app module, using the application plugin in the modules build.gradle file

Now if you’re building a single module application then this will be the only module-type plugin that you will be using throughout your project. In single module projects, this base module will contain all of your applications responsibilities — be in User Interface, Networking, Data etc

If you’re building a multi-module application, then the application module will still be the installed module, but the way this application module operates will vary depend on what it is you are building.

Common/Shared Modules

You can essentially use these modules to separate out related areas of your project so that they are decoupled from the main module of your project. Let’s call this the core module.

This core module will contain all of the shared business logic, data operations, caching etc that is used by all dynamic modules. In this case, you are promoting code re-use as all of these aspects can be shared between your dynamic modules. Separating core logic can also help to create a clear separation of concerns that makes your code easier to understand, test and maintain across your team

Core modules that contain android framework references will need to use the library plugin:

Dynamic Feature Modules

These feature modules are going to contain specific features of our application which can help us to again decouple different responsibilities. Now, the way that these are defined will depend on the kind of multi-project application that you are building.

Dynamic App Modules can be used to decouple specific features and resources of your application into their own module, to then be used as part of the new App Bundle format which allows us to dynamically deliver individual features to users. This means we can reduce the initial install size of our applications, instead allowing users to download specific features at run-time as and when they are required.

Dynamic feature modules will contain pure feature implementations whilst still having a reference to the base module of the application. The manifest file contained within it has some additional information regarding the distribution of this module.

We can define a module as a dynamic feature module by using the provided plugin below:

Wrap-up

I will be building a demo sample with you ground up in the next articles, to try and explain the above concept in a practical manner. Most of what I am blogging about is still work in progress, and I would appreciate PR’s and guest comments on these articles moving on.

Remember to share and leave comments 🙂

Happy Coding!

Building for scale at d.light Solar, our Android Journey [Part 1]

Building for scale at d.light Solar, our Android Journey [Part 1]

Seven months ago, I joined d.light Solar to join the Platform Team, to specifically work on our Android Apps. They had a vision to go head on on Mobile Solutions, and Android was the favourite.

d.light has sold over 20 million solar lamps improving the lives of over 95 million people in over 65 countries, and the business wanted to build various mobile solutions to help them scale even more.

The challenge was building 6 different apps, each with different requirements, and varying across 35 markets. As the mobile team, this meant us building 6 apps as part of our version 4, dubbed Atlas, in around 8-12 months.

Whaaaat! This is ridiculous…

Like most Android Apps developers, the idea was to build these apps as 6 different apps, but this meant we had to build common modules many times in the process, not forgetting common things like tests and deployments setup.

So I had to think of a better and simpler option, like building all these features as one monolith app. But this would mean having one bulky APK, which would not be favourable especially during updates. I had to look for a better engineering solution to our problem.

Introducing App Modularization

In Google I/O 2018, Android App Bundles (aab) were introduced. One of the benefits was dynamic delivery, automatic multi-APK distribution, smaller APK size and dynamic feature modules. This opened way to modularization on Android Apps, and this looked like our solution. Building the 6 apps as dynamic modules , but how?👀

The solution was to leverage Dynamic App Modules, to only build one APK, with each of the 6 apps built in as a feature module inside it, and called it Atlas. So lets explore app modularization and what it meant for us at d.light

Modular programming is a software design technique to separate functionality into independent, interchangeable modules, so that each contains everything necessary to execute a specific functionality.

For us, this was easy. Each of the 6 apps had it’s own specific functional requirements, and we used these as different modules for the app.

What language and why?

The next big question was which language to use, good old Java or the new shinny Kotlin. The answer was simple, Kotlin.

Kotlin is more modern, and offers a lot of new features which include lambdas, extension functions, less boilerplate code, more conscience and is more safe than Java. Coroutines also mean we can write asynchronous code. Aside from this, Google made it a first class language in Android development!

Application Architecture

The app will primary use the MVVM Architecture, which is the Model-View-View-Model. This is one of the most efficient architectures in Android development. It provides loose coupling of the components, and offer two important components, the View Model and LiveData.

  • The ViewModel holds the data across lifecycle changes, improving the app performance greatly
  • The LiveData provides a reactive way of getting data from the database, without user initiated refreshes.

The app also leverages Data Binding a lot, so data is binded to the UI at the layout level. The advantage is with new changes, we only change the layout and the data source, without any other change on the app code. This results in faster development time.

Communication

With the current number of modules, and the growing needs of the business, I had to think of an efficient way to handle communication between existing modules and the new modules we had to build in the near future, the result an event driven communication style.

By leveraging the event-driven architecture, communication between modules becomes easy, and more decoupled, resulting in better, cleaner and more testable code. The preferred option was Eventbus, due do to its robust nature and simplicity

Conclusion

Most of this was inspired by Plaid, which is a very nice starting point and offered a lot of reference points for me. This first part was mainly introducing the technologies, just to give an overall overview about the problem and the technologies I picked to tackle them. In the next part, I will deep dive into Android Modularization, and how we leverage it to build at d.light.

Remember to share and leave comments 🙂

Happy Coding!

Rest API Pagination with Paging Library

Rest API Pagination with Paging Library

Howdy guys! Am back after 7 months of exciting period in my life. Just to mention a few things, I just left TwigaFoods at the end of January to join dLight Solar as the Lead Mobile Engineer there! It’s been an amazing experience working for them, and would like to appreciate TwigaFoods community for the amazing one year we spent together. I also got a new ride, a BMW 3 Series, and have been racing a lot, mostly explaining my absence here. I will however start posting 3 articles a week starting this week 🙂

Almost every REST API your app call requires to handle pagination. When calling a REST API for resource delivering all of the results could be time-consuming, a REST API will typically make you paginate through the results. If you are trying to support pagination on a client you need to handle it gracefully.

Let’s say that there’s an API endpoint that returns a list of users. In the database of the API, there are 100,000+ users. It would be impractical to fetch all 100,000 users from the API all in one request. In fact, we would probably get an OutOfMemory exception. To avoid this, we want to paginate through our list of the user when making requests to our API.

Paging Library

The new paging library makes it easier for your app to gradually load information as needed from a REST API, without overloading the device or waiting too long for an all result.This library contains several classes to streamline the process of requesting data as you need it. These classes also work seamlessly with existing architecture components, like Room.

Adding Components to your Project

Architecture Components are available from Google’s Maven repository. To use them, follow these steps:

Open the build.gradle file for your project and add the line as shown below:

Add Architecture Components

In this tutorial, we are using LiveData, and ViewModel.

Open the build.gradle file for your app or module and add the artifacts that you need as dependencies:

Setting up Retrofit for Pagination

The code samples below for making the API calls are using Retrofit with GSON.We are working with the GitHub API and making a call to the GitHub User endpoint.

Now, let’s write our class that will generate our RetrofitService.

Create ItemKeyedDataSource

Use ItemKeyedDataSource class to define a data source.It uses for incremental data loading for paging keyed content, where loaded content uses previously loaded items as input to next loads.

Implement a DataSource using ItemKeyedDataSource if you need to use data from item N - 1 to load item N. This is common, for example, in sorted database queries where attributes of the item such just before the next query define how to execute it.

To implement, extend ItemKeyedDataSourcesubclass.

DataSourceFactory

A simple data source factory which also provides a way to observe the last created data source. This allows us to channel its network request status etc back to the UI.

Create ViewModel

In the ViewModel, we would extend from the Architecture Component ViewModel, and then we would keep a reference to that LiveData of our PagedList.

LivePagedListBuilder:This class generates a LiveData<PagedList> from the DataSource.Factory you provide.

PagedList: A PagedList is a List which loads its data in chunks (pages) from a DataSource.All data in a PagedList is loaded from its DataSource. Creating a PagedList loads data from the DataSource immediately, and should, for this reason, be done on a background thread. The constructed PagedList may then be passed to and used on the UI thread. This is done to prevent passing a list with no loaded content to the UI thread, which should generally not be presented to the user.

Create ProgressBar as Footer in a RecyclerView

Create RecyclerView with 2 type of items one is our usual items the second is a progress bar, then we need to listen NetworkState LiveData and decide are we going to show ProgressBar or not.

Now, set the Network State and add or remove ProgressBar in Adapter.

hasExtraRow() check the Network State and return true or false.

To tell the PagedListAdapter how to compute the difference between the two elements, you’ll need to implement a new class, DiffCallback.Here, you will define two things.

You will define how to compute whether the contents are the same, and how to define whether the items are the same.
Let’s look at the adapter.So our adapter would extend PagedListAdapter, and then it will connect the user, which is the information that’s being displayed, with the user ViewHolder.

We define the callback, the DIFF_CALLBACK, for our user objects and then in onBindViewHolder, all we need to do is bind the item to the ViewHolder.

Create RecyclerView

In the onCreate, we get the reference to our ViewModel and get the reference to the RecyclerView, and we create our adapter.

Conclusion

I will write another article covering Paging Library in more detail. Keep subscribed here to get more updates. Feel free to leave a comment and share your knowledge.

Happy Coding!

Introduction to Testing in Android

Introduction to Testing in Android

Hi, do you want to start writing tests for your Android apps and make them stable during constant new feature implementations?  Let’s start a series about Android Testing.

As testing is one of my weakest areas in Android – I will be learning stuff just as most of you. It’s just that every developer will reach the point where you can build complex apps, but quality – is still behind. Here come tests, just like you, I want to learn how much it is possible to automate tests on Android

Types of Tests on Android

Basically, there are two types depending on where they run: Local and Instrumented tests. And  two categories depending on what those tests are meant for: Unit Tests and UI Tests

Here’s a pyramid from official Google docs which I modified a bit, to show which test types run on computer or Android device

Tests in Android

As you see the second one says integrated, but by that, they mean integrated unit tests. And they suggest to write 70% local unit tests (Small testes), 20% integrated unit tests (Medium tests) and 10% UI tests (Large tests). I’ll trust this data for now because they definitely know much more about testing than I do

Local Tests

Local are tests which run on your computer. They don’t know anything about Android framework, even though you can import classes from it – you’ll get an exception when trying to call any methods. This is made intentionally so that they force you to write unit tests that do not depend on Android framework

You can monitor the elements of the Android framework with which your app interacts by running unit tests against a modified version of android.jar. This JAR file doesn’t contain any code, so your app’s calls to the Android framework throw exceptions by default

But there’s a way you can mimic Android framework – by mocking its methods with Mockito library. Basically how it works is you declare your own implementation for different methods. And since you do know class/method names from Android framework (they just throw exceptions) – you can get by

Also, there’s a great library called Robolectric, with it you don’t need to mock Android framework’s methods since they’re stubbed by Robolectric. They say it’s very close to running instrumented tests.

Instrumented Unit Tests

Those do have access to Android framework, since they run on an actual device or emulator. They’re great if you need to access Android framework’s classes (Parcelable, Context etc), testing databases and don’t want to mock methods, rely on Robolectric. But they still don’t have any UI

And to run those you need to build and install an apk to a device, so they are slower than local unit tests

UI Tests

Those obviously fall into integrated tests category, but they are not unit tests. UI tests feel the most natural to me simply because that’s the way I currently test apps: navigate, interact, verify results, look for crashes, debug

There’s one problem with it – it gets incredibly boring to go through the same parts of your app after each new feature implemented. Which means you skip testing some parts and as a result, you can get a fatal crash that has been around for 2 weeks and you didn’t know about it. Well, something like that.

Espresso

This framework lets you select an activity you want to test and write the whole list of interactions like clicks, typing, launch different activities and then verify that UI is in the correct state. And the cool part is that you see those interactions just like you would do them yourself. Also starting from Android 8 it’s possible to open other apps

UI Automator

It seems to be very similar to Espresso. But for now, I think Espresso is a more mainstream framework and is more developed. We’ll get deeper into those differences in the future posts

ADB UI Testing

There’re also two adb tools: monkeyrunner and monkey. Monkey runners lets your write some Python scripts to navigate through your app, make some interactions and look for crashes, take screenshots

Monkey is a simple adb tool where you just declare number of actions to perform and it runs through your app clicking on stuff and looking for crashes.

Conclusion

These are the main ways of testing Android apps. But they mean nothing until you make a mind change to TDD or just automating UI tests. In the following posts, we’ll get deep into each of those categories with actual examples of tests and mindset behind what part you’d test

If you do write tests for your apps – feel free to leave a comment and share your knowledge.

Happy Coding!

Introduction to Flutter in Android

Introduction to Flutter in Android

Flutter is an open source beta framework by Google for mobile UI to build high-quality native (super fast) interfaces for both iOS and Android. Dart is used as a programming language inside Flutter. Dart is similar to other modern languages such as Kotlin and Swift, and can be transcompiled into JavaScript code.

Flutter allows for a reactive and declarative style of programming and as a cross-platform framework, Flutter most closely resembles React Native. Unlike React Native, however, Flutter does not need to use a Javascript bridge, which can improve app startup times and overall performance. Dart achieves this by using Ahead-Of-Time or AOT compilation.

Another unique aspect of Dart is that it can also use Just-In-Time or JIT compilation. JIT compilation with Flutter improves the development workflow by allowing hot reload capability to refresh the UI during development without the need for an entirely new build.

As you’ll see in this tutorial, the Flutter framework is heavily built around the idea of widgets. In Flutter, widgets are not used just for the views of your app, but also for entire screens and even for the app itself.

Today, we are going be properly install Flutter and its required components and also run a demo app on both the Android Emulator.

Setting Up Environment

Flutter development can be done on macOS, Linux, or Windows. We’ll use Android Studio for this tutorial.

Instructions for setting up your development machine can be found here. The basic steps vary by platform (mine = macOS), but for the most part are:

  • Clone the Flutter git repository
  • Add the Flutter bin directory to your path
  • Run the flutter doctor command, which installs the Flutter framework including Dart and alerts you to any missing dependencies
  • Install missing dependencies
  • Set up your IDE with a Flutter plugin/extension
  • Test drive an app

Using Android Studio

With Android studio, it is pretty easy and straight forward.

Open Android studio (This is me assuming you already have Android studio up and running on your computer)

Open Android Studio > Preferences.. > Plugins and select Browse repositories.

Here you are going to install 2 plugins: Dart and Flutter, so on the search bar type in “Dart

I already have it installed, so you would notice I don’t have regular green-issh “install” button. So you just click on install and wait out the process.

Then also on the search bar type in “Flutter

So just install and restart your IDE.

On restart you would notice that Android studio now has Flutter project as an option.

Select Start a new Flutter project > Flutter Application

You then proceed to this screen.

You don’t have the Flutter SDK installed, but Android Studio can help you with that. Just select the directory you want it installed in and click on Install SDK… Android studio will clone the repo into the specified directory and voila you have the SDK installed. You need to do one more thing, but go ahead and finish the project.

Locate the folder you specified for the Flutter SDK, then open a new terminal at that folder.

At this stage you can either temporarily set our PATH variable or permanently add Fluter to you PATH.

To add temporarily,

To add permanently,

then run echo $PATH to confirm if added successfully.

Next run the following command to see if there are any dependencies you need to install to complete the setup:

This command checks your environment and displays a report to the terminal window. The Dart SDK is bundled with Flutter; it is not necessary to install Dart separately.

The first time you run a flutter command (such as flutter doctor), it downloads its own dependencies and compiles itself. Subsequent runs should be much faster.

The following sections describe how to perform these tasks and finish the setup process.

Once you have installed any missing dependencies, run the flutter doctorcommand again to verify that you’ve set everything up correctly.

So you ready, thats all, all set up.

Lets return to the project we created on Android studio. We have a default project provided by Flutter.

You can either plug in your a mobile device, run on an Android emulator or iOS simulator. Locate the main Android Studio toolbar, select which you want and then click PLAY.

Flutter offers a fast development cycle with hot reload, the ability to reload the code of a live running app without restarting or losing app state. Simply make a change to your source code, tell your IDE want to hot reload, and see the change in your simulator, emulator, or device.

  • Change the string
    'You have pushed the button this many times:' to
    'You have clicked the button this many times:'
  • Do not press the ‘Stop’ button; let your app continue to run.
  • Click the Hot Reload button (the button with the lightning bolt icon).

You should see the updated string in the running app almost immediately.

Thanks for reading and hope you enjoy Flutter. Feel free to leave a comment below if you have any issues, suggestions, etc.

Happy Coding!