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.

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.


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.


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.


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.


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!

ButterKnife  – A Viewbinding library for Android

ButterKnife  – A Viewbinding library for Android

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

Let’s get started!

What is Butterknife?

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

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

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

Getting Started

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

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

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

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



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

Binding Views, Resources and Event Listeners

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

Here’s an example of this “injection”:

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

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

You can refer to the Butterknife Documentation on this link


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

Happy Coding!

Android Data Binding

Android Data Binding

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

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

Project Setup

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

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

Data Binding

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

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

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

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

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

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

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


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

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


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

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

Happy Coding!