Understanding Dependency Injection A Tiny Bit More

Today I had a minor epiphany. I was working on a unit test on a class method, and had a rather annoying time with it because the class (a ViewModel) uses an instance of a different class (a repository) to do things. There is a coroutine involved, so things got a bit hairy until I watched a tutorial video that essentially suggested a dependency required for testing to be added as parameter for the class’s constructor.

This required me to modify the actual class, and when I was done I just realized what this is about. It’s dependency injection!

Sure, I’ve written about it before (in an attempt to understand it), but it’s only when I’m actively working on adding unit tests that I experienced the actual value of D.I. Pretty neat!


Building Custom TimePicker Dialog Preference in Android

In the spaced repetition app I’m building, I wanted to allow people to pick a time for the study reminder notifications to show up on. There is a built-in AndroidX Preference Library that is meant to help with this, however I found that there’s no built-in way to display a TimePicker dialog as part of the preference option. Some tinkering are still required, and here’s the solution that works for me.


Before heading to the code, here’s a quick recap of what will be needed. Think of them as the building blocks that have to connect together.

  1. A class that derives from DialogPreference. This part is for managing the Preference aspect of the dialog preference to be displayed, such as its message, buttons, as well as for saving and retrieving the value selected. The library has some built-in dialog preferences (EditTextPreference,  ListPreferenceMultiSelectListPreference), but no such thing as TimePickerPreference, so we’ll have to make ourselves here.
  2. A class that derives from PreferenceDialogFragmentCompat. This part is for managing the visual aspect of the dialog preference to be displayed. This is where we will actually create and display the TimePicker, for instance.
  3. XML layout for the main preference page. This is used to for the visual aspect of the preferences page that’s shown to the user.
  4. Lastly, a fragment that derives from PreferenceFragmentCompat, which essentially is a special type of fragment that’s meant to be used for displaying the preferences page based on the XML layout, and for wrangling various display options related to it.

1. TimePickerPreference

First thing we want to make is the TimePickerPreference. Here’s how my code looks like:

package black.old.spacedrepetitionowl
import android.content.Context
import android.util.AttributeSet
import androidx.preference.DialogPreference
// This class is used in our preference where user can pick a time for notifications to appear.
// Specifically, this class is responsible for saving/retrieving preference data.
class TimepickerPreference(context: Context?, attrs: AttributeSet?) : DialogPreference(context, attrs) {
// Get saved preference value (in minutes from midnight, so 1 AM is represented as 1*60 here
fun getPersistedMinutesFromMidnight(): Int {
return super.getPersistedInt(DEFAULT_MINUTES_FROM_MIDNIGHT)
// Save preference
fun persistMinutesFromMidnight(minutesFromMidnight: Int) {
override fun onSetInitialValue(defaultValue: Any?) {
summary = minutesFromMidnightToHourlyTime(getPersistedMinutesFromMidnight())
// Mostly for default values
companion object {
// By default we want notification to appear at 9 AM each time.
private const val DEFAULT_HOUR = 9

Above, I override onSetInitialValue() so that I can fill the preference’s summary with the actual time. The idea is to allow people to see the currently selected time, which should look like this:

A preference with the 10:30 value written in the summary area of the preference.

With custom dialog preference like this, I found that the summary area is what’s commonly used to show the current value of that preference.

The two functions persistMinutesFromMidnight() and getPersistedMinutesFromMidnight() are to be used for saving and retrieving the value related to this preference.

2. TimePickerPreferenceDialog

After the preference aspect is created, now we set up the actual dialog. Here’s the code that I have:

package black.old.spacedrepetitionowl
import android.content.Context
import android.os.Bundle
import android.view.View
import android.widget.TimePicker
import androidx.preference.PreferenceDialogFragmentCompat
class TimePickerPreferenceDialog : PreferenceDialogFragmentCompat() {
lateinit var timepicker: TimePicker
override fun onCreateDialogView(context: Context?): View {
timepicker = TimePicker(context)
return timepicker
override fun onBindDialogView(view: View?) {
val minutesAfterMidnight = (preference as TimepickerPreference)
timepicker.hour = minutesAfterMidnight / 60
timepicker.minute = minutesAfterMidnight % 60
override fun onDialogClosed(positiveResult: Boolean) {
// Save settings
if(positiveResult) {
val minutesAfterMidnight = (timepicker.hour * 60) + timepicker.minute
(preference as TimepickerPreference).persistMinutesFromMidnight(minutesAfterMidnight)
preference.summary = minutesFromMidnightToHourlyTime(minutesAfterMidnight)
companion object {
fun newInstance(key: String): TimePickerPreferenceDialog {
val fragment = TimePickerPreferenceDialog()
val bundle = Bundle(1)
bundle.putString(ARG_KEY, key)
fragment.arguments = bundle
return fragment

Inside onCreateDialogView(), we generate the TimePicker to be displayed.

Inside onBindDialogView(), we grab the current hour/minute preference value, and set that value into the TimePicker. The goal is to make it so that when someone first opens the TimePicker dialog, the clock already shows the current value instead of starting from zero. (preference as TimepickerPreference) is needed here because without it, the compiler does not now that the current preference is a custom TimePickerPreference, and hence will not be able to find the function we need.

Inside onDialogClosed(), we save the value selected by the user after clicking the positive button.

For more information about the NewInstance pattern, this article will be helpful.

3. XML Layout

Here’s my preference XML file:

<?xml version="1.0" encoding="utf-8"?>
<androidx.preference.PreferenceScreen xmlns:android="">
android:title="Notification time"
android:summary="This will programmatically show current notification time."
android:defaultValue="90" />
view raw preference.xml hosted with ❤ by GitHub

The interesting part might be <black.old.spacedrepetitionowl.TimepickerPreference> which indeed is the class we created on step 1. During run-time, the android:summary part is programmatically modified and filled in both within TimePickerPreference (on initial opening of the preference screen), and TimePickerDialogPreference (after user picked a time).

4. PreferenceFragment

This is the regular fragment that we’ll use to display the preference screen. Here’s my file:

package black.old.spacedrepetitionowl
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.preference.Preference
import androidx.preference.PreferenceFragmentCompat
* A simple [Fragment] subclass.
class PreferenceFragment : PreferenceFragmentCompat() {
private val DIALOG_FRAGMENT_TAG = "TimePickerDialog"
override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
setPreferencesFromResource(R.xml.preference, rootKey)
override fun onDisplayPreferenceDialog(preference: Preference?) {
if(preference is TimepickerPreference) {
val timepickerdialog = TimePickerPreferenceDialog.newInstance(preference.key)
timepickerdialog.setTargetFragment(this, 0), DIALOG_FRAGMENT_TAG)
else {

First, we’re pulling the XML layout inside onCreatePreferences().

Next, since we want to display our own custom dialog preference, we need to override onDisplayPreferenceDialog(). Here, we specifically want to check if the currently selected preference is our custom preference, TimePickerPreference. If it is, we instantiate a new TimePickerPreferenceDialog and display it. If it’s a different type of dialog preference (let’s say it’s one of the three built-in dialog preferences mentioned earlier), we let it be handled automatically by the superclass.

And that’s it! This is just a small example but hopefully is a good starting point if you want to create a different kind of custom dialog preference 🙂


Fun with ViewModel and LiveData: Sending Informations between Fragments

In Android development, there are a few different ways to send informations between one fragment to another. As of September 2020, the recommended way to allow for this communication is to use LiveData exposed by a shared ViewModel.

The steps are relatively simple. Suppose that we want to send data from Fragment A to Fragment B:

  1. Create a ViewModel
  2. Have Fragment A and Fragment B share that same ViewModel.
  3. Create a LiveData inside the ViewModel to contain the data that’s to be passed from A to B.
  4. Assign or update value to the LiveData object inside Fragment A, usually with the help of a public method inside the ViewModel to assign or update the value.
  5. Have Fragment B observe the LiveData inside it onCreate() , and make use of the data there.

General Mechanism for Scheduling Notification in Android

This article is more of a quick note about what’s involved when your Android app needs to create a notification and schedule it to appear at some time in the future. There’s a lot of articles out there that goes in details about the implementation. Think of this article as more of a summary.

Link Programming

Link: Adding Click Listener to RecyclerView using Kotlin

Recently I needed to figure out how to add click listeners to RecyclerView, in my app that’s using Kotlin as language. Kotlin supports higher-order functions, so the click listener solution can look more concise and elegant, avoiding the need to add interfaces like in Java. Andreas Jakl wrote a detailed tutorial about it here.


Kotlin: Using MediatorLiveData to Use Data from Two Tables at Once

With my current app, the main data is Subjects, where each Subject have multiple Reminders tied to it. For this purpose, I have a couple of tables in the database, which in its simplified form can be seen as below:

Subject table with:

  1. Subject ID
  2. Subject title

Reminder table with:

  1. Reminder ID
  2. Reminder timestamp
  3. Subject ID

I’m using Room for database and LiveData to pull data from the tables. The data then gets supplied to a RecyclerView, where each RecyclerView item will display a Subject with its Reminders.

RecyclerView where each row is a Subject and its four Reminder dates.

The tricky part is that, since there are two tables, I have two separate methods returning LiveData object from each table. Most tutorials out there assume the use of only one LiveData to be observed by the RecyclerView, so it can get confusing when there’s two LiveData at once.

I found a smart solution on Stack Overflow that makes use of MediatorLiveData and Kotlin’s Pair to make the whole thing work. This article is an attempt to expand on that solution by writing down my understanding of it.

This article assumes familiarity with Android concepts for RecyclerView, Room, ViewModel, and LiveData.

Create a “combination” MediatorLiveData class

The first thing to do is to create a class that extends MediatorLiveData. The interesting part is that we need to use Pair<List<Subject>, List<Reminder>> as MediatorLiveData’s type.

After that, we simply construct the class by sending it LiveData<List<Subject>> and LiveData<List<Reminder>> as constructor parameters, then put those two inside a Pair, and finally set the Pair as the MediatorLiveData object’s value.

import androidx.lifecycle.LiveData
import androidx.lifecycle.MediatorLiveData
// This class ia a MediatorLiveData created since I have two different sources of data:
// – subjects table
// – reminders table
// Since they then become two separate LiveData, and I need both to fill in the data
// on the main RecyclerView, then we're using a MediatorLiveData to grab both LiveData
// and add them as sources, so that we can notify observers when any of the data gets
// updated.
class CombinedSubjectReminders(
ldSubject: LiveData<List<Subject>>,
ldReminder: LiveData<List<Reminder>>
) : MediatorLiveData<Pair<List<Subject>, List<Reminder>>>() {
private var listSubject: List<Subject> = emptyList()
private var listReminder: List<Reminder> = emptyList()
init {
value = Pair(listSubject, listReminder)
addSource(ldSubject) {
if( it != null ) listSubject = it
value = Pair(listSubject, listReminder)
addSource(ldReminder) {
if( it != null ) listReminder = it
value = Pair(listSubject, listReminder)
Example of a MediatorLiveData class to handle two LiveDatas at once.

That is pretty much where the magic lies. The potentially tricky part is the addSource method and the value variable, both of which are built-in features of the MediatorLiveData.

Inside ViewModel

Inside the ViewModel, we call the repository’s methods for pulling LiveData from each table, then we return a “combination” object as we describe in the class above, and put in the LiveData as its parameters.

fun getSubjects(): LiveData<List<Subject>>? {
return sroRepository.getSubjects()
fun getReminders(): LiveData<List<Reminder>>? {
return sroRepository.getReminders()
fun getAllData(): CombinedSubjectReminders? {
var ldSubjects = getSubjects()
var ldReminders = getReminders()
if (ldSubjects != null && ldReminders != null) {
return CombinedSubjectReminders(ldSubjects, ldReminders)
return null
Methods inside ViewModel to grab two LiveData from repository and put them into one MediatorLiveData

Inside RecyclerViewAdapter

Inside the adapter, we modify its constructor to accept two Lists as parameters, the List<Subject> and the List<Reminder>.

class SubjectRecyclerViewAdapter(
val subjects: List<Subject>,
val reminders: List<Reminder>,
val listener: OnListFragmentInteractionListener?
) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
Put in the two List<> as constructor parameters in RecyclerViewAdapter

Observe the MediatorLiveData

Finally, inside the fragment or activity that has the RecyclerView, we observe the returned MediatorLiveData from the ViewModel. When there’s any change, the observer gives a Pair containing a List<Subject> and a List<Reminder>. We can then put those two as the parameter of the adapter.

mainViewModel = ViewModelProvider(activity!!).get(
// New observer
Observer { subjectsAndRemindersPair ->
view.sro_subject_list.adapter = SubjectRecyclerViewAdapter(
Observe the MediatorLiveData given by ViewModel, and update RecyclerViewAdapter accordingly.

Note how the Observer pattern uses a lambda with subjectsAndRemindersPair as the parameter. That is essentially the type of the MediatorLiveData in question, and by default Kotlin call that parameter it. I renamed it to subjectsAndRemindersPair to make it easier to understand.


Strategies for Creating A Single RecyclerView with Multiple ViewHolders

This article assumes familiarity with creating a RecyclerView using a single ViewHolder for each item, which is the most common use case.

Here are the possible cases where a RecyclerView might use an adapter with multiple ViewHolders instead:

A RecyclerView that uses two different layouts for each item based on odd/even position.

Case One

Have one RecyclerView to display different layouts for different items at the same time, based on certain conditions. Just as an example, here I have a RecyclerView that uses two different layouts for each item based on odd/even position.

A RecyclerView that uses identical layout for each item.

Case Two

Have one RecyclerView to display the same layout for each item. However, based on user action on certain conditions (such as during sorting or filtering action), the same RecyclerView will display the same data using a different layout. As an example, here’s a RecyclerView that uses just one layout for each item. Use your own imagination for an example where the RecyclerView at a different time uses a different layout instead.

Case 1

Here’s the general method. I’m only listing areas that differ from the usual case of RecyclerView with just one ViewHolder:

  1. We now have to create the multiple ViewHolder classes first. I prefer them to be inner classes of the custom RecyclerView.Adapter class. Pretty self-explanatory, the only possible gotcha/oddity here is that inside the class’s constructor, we create variables that directly access specific views inside a certain layout, without the class knowing about which layout it is related to.
  2. The RecyclerView adapter now must extend the more generic RecyclerView.Adapter<RecyclerView.ViewHolder>class instead of using the single custom ViewHolder class as the generic type.
  3. The RecyclerView now must override getItemViewType(), which is used to decide which ViewHolder class to be used on a certain item position in the RecyclerView.
  4. The method onCreateViewHolder() must now return the more generic RecyclerView.ViewHolder
  5. The method onBindViewHolder() must now use the more generic RecyclerView.ViewHolder object as its first parameter.

Case 2

  1. Have a variable to determine which ViewHolder should be used by the RecylerView. This will usually be inside the fragment or activity.
  2. Pass that variable as one of the parameters for constructing the RecyclerView’s adapter.
  3. Inside the adapter, create the multiple ViewHolder classes first. I prefer them to be inner classes of the custom RecyclerView.Adapter class. Pretty self-explanatory, the only possible gotcha/oddity here is that inside the class’s constructor, we create variables that directly access specific views inside a certain layout, without the class knowing about which layout it is related to.
  4. The RecyclerView adapter now must extend the more generic RecyclerView.Adapter<RecyclerView.ViewHolder>class instead of using the single custom ViewHolder class as the generic type.
  5. The RecyclerView adapter now must override getItemViewType(), and check the variable from step 2 to determine which ViewHolder to use.
  6. The method onCreateViewHolder() must now return the more generic RecyclerView.ViewHolder
  7. The method onBindViewHolder() must now use the more generic RecyclerView.ViewHolder object as its first parameter.

Data Binding with Kotlin; Why?

I came across the Data Binding resources page for Android, and reading through it got me questioning. Why is such setup necessary, when Kotlin extensions allows for super easy view binding already (example below)?

// Using R.layout.activity_main from the 'main' source set
class MyActivity : Activity() {
override fun onCreate(savedInstanceState: Bundle?) {
// Instead of findViewById<TextView>(
textView.setText("Hello, world!")
Example of view binding using Kotlin Extensions (source)

As it turns out, there’s quite a difference as explained on a Reddit comment that I pasted below:

Hey! Developer Advocate for Android at Google here!

I wanted to add a bit of background here. Kotlin Extensions with synthetic views was never intentionally “recommended” though that shouldn’t be taken as a recommendation to not use them. If they’re working for you please feel free to continue using them in your app!

We’ve been shifting away from them (e.g. we don’t teach them in the Udacity course) because they expose a global namespace of ids that’s unrelated to the layout that’s actually inflated with no checks against invalid lookups, are Kotlin only, and don’t expose nullability when views are only present in some configuration. All together, these issues cause the API to increase number of crashes for Android apps.

On the other hand, they do offer a lightweight API that can help simplify view lookups. In this space it’s also worth taking a look at Data Binding which also does automatic view lookups – as well as integrates with LiveData to automatically update your views as data changes.

Today, there’s a few options in this space that work:

  • Data Binding is the recommendation for view lookup as well as binding, but it does add a bit of overhead when compared to Android Kotlin Extensions. It’s worth taking a look to see if this is a good fit for your app. Data Binding also allows you to observe LiveData to bind views automatically when data changes. Compared to Kotlin Extensions, it adds compile time checking of view lookups and type safety.
  • Android Kotlin Extensions is not officially recommended (which is not the same as recommendation against). It does come with the issues mentioned above, so for our code we’re not using them.
  • Butter Knife is another solution that is extremely popular and works for both Kotlin and the Java Programming Language.

Reading through the comments here there’s a lot of developers that are having great luck with Kotlin Extensions. That’s great – and something we’ll keep in mind as we look at ways to continue improving our APIs. If you haven’t taken a look at Data Binding, definitely give it a shot.

As an aside, our internal code style guide is not intended to be directly applied outside of our codebase. For example, we use mPrefixVariables, but there’s no reason that every app should follow that style.

On ButterKnife

The quote mentions ButterKnife, so it’s probably worth mentioning also that the Github page for ButterKnife mentions that development for it is being winded down, and it recommends to use View Binding instead.

Data Binding vs View Binding

Now that these two concepts are being mentioned, what are the differences? From the View Binding documentation page:

View binding and the data binding library both generate binding classes that you can use to reference views directly. However, there are notable differences:

  • The data binding library processes only data binding layouts created using the <layout> tag.
  • View binding doesn’t support layout variables or layout expressions, so it can’t be used to bind layouts with data in XML.

Stack Overflow: Android : Difference between DataBinding and ViewBinding


Digging into Coroutines

With Kotlin comes one of its most famous features: coroutines.

Javanese is my first language. No, not the Java programming language. Javanese. So whenever I hear a foreign word like coroutines, nothing shows up in my mind. It has no meaning. This post is an attempt to dig into the word to give my brain some understanding of it.

Coroutines, Threads, Processes

First, here’s what the official documentation says about it (emphasis mine):

One can think of a coroutine as a light-weight thread. Like threads, coroutines can run in parallel, wait for each other and communicate. The biggest difference is that coroutines are very cheap, almost free: we can create thousands of them, and pay very little in terms of performance. True threads, on the other hand, are expensive to start and keep around. A thousand threads can be a serious challenge for a modern machine.

“Your first coroutine with Kotlin”

I know that coroutines is a way to do asynchronous programming, and from the information above, it seems to have these three major points:

  1. Analogous to a light-weight thread,
  2. Multiple coroutines can run together at the same time, they can wait for each other, and also communicate to each other,
  3. Having a lot of them does not hurt performance.

I’m currently using Kotlin for programming Android apps, so the next step seems to be to figure out what exactly a thread is in this context. Here’s what the documentation says (emphasis mine):

When an application component starts and the application does not have any other components running, the Android system starts a new Linux process for the application with a single thread of execution. By default, all components of the same application run in the same process and thread (called the “main” thread). If an application component starts and there already exists a process for that application (because another component from the application exists), then the component is started within that process and uses the same thread of execution.

Android Developers — Processes and Threads

So from here, it seems like within Linux there is a concept of “process”, and also “thread of execution”. According to Wikipedia:

In computing, a process is the instance of a computer program that is being executed by one or many threads. It contains the program code and its activity. Depending on the operating system (OS), a process may be made up of multiple threads of execution that execute instructions concurrently

Wikipedia — Process (computing)

This helps understanding what a “process” is. One of the definition from Merriam-Webster is: “something going on”. So in this context, a process is the idea of an app that’s currently running within Android. That’s simple enough.

Also, it just blew my mind right now that this is why a processor is called that —again, English is not my first language—it’s basically the thing that runs the apps.

Let’s have a few seconds of visual break:

Photo by Tran Mau Tri Tam on Unsplash

Wikipedia has this to say about thread of executions:

In computer science, a thread of execution is the smallest sequence of programmed instructions that can be managed independently by a scheduler, which is typically a part of the operating system.[1] The implementation of threads and processes differs between operating systems, but in most cases a thread is a component of a process. Multiple threads can exist within one process, executing concurrently and sharing resources such as memory, while different processes do not share these resources.

Wikipedia — Thread (computing)

Thread, according to Merriam-Webster:

3 : something continuous or drawn out: such as

a : a line of reasoning or train of thought that connects the parts in a sequence (as of ideas or events)

So from the two explanations above, a process seems to be the whole existence of a running app, while a thread is the smaller element within the process.

For example in Instagram, a thread might be the start from finish when someone uploads a new picture (tap plus icon, find the image, add filter, add description, click upload, wait for it to be sent, have the image displayed). I don’t know if that’s technically accurate, but probably a good approximation.

The Wikipedia about thread also has this useful section about the difference between processes and threads:

Threads differ from traditional multitasking operating-system processes in several ways:

  • processes are typically independent, while threads exist as subsets of a process
  • processes carry considerably more state information than threads, whereas multiple threads within a process share process state as well as memory and other resources
  • processes have separate address spaces, whereas threads share their address space
  • processes interact only through system-provided inter-process communication mechanisms
  • context switching between threads in the same process typically occurs faster than context switching between processes

It also has this useful image:

A process with two threads of execution, running on one processor

So far we’ve learned about what a process and a thread is. And, specifically within Android, we have learned that a running app is given one process and one main thread.

So a coroutine is like a thread, and has similar behaviors, except that it’s light-weight and can perform better.

That’s a good start. Now let’s see if we can figure out what it means with multiple coroutines running in parallel, communicating and coordinating with each other.

Photo by Gaelle Marcel on Unsplash

Here is another explanation of what coroutine is:

coroutine A program component that allows structuring of a program in an unusual way. A coroutine resembles a subroutine, with one important difference. A subroutine has a subordinate position relative to the main routine: it is called and then returns. Coroutines, however, have a symmetric relation: each can call the other. Thus a coroutine is resumed at a point immediately following its call of another coroutine; it never returns, but terminates its operation by calling (resuming) another coroutine. — coroutine

What even is a subroutine?

In computer programming, a subroutine is a sequence of program instructions that performs a specific task, packaged as a unit. This unit can then be used in programs wherever that particular task should be performed.

Subroutines may be defined within programs, or separately in libraries that can be used by many programs. In different programming languages, a subroutine may be called a procedure, a function, a routine, a method, or a subprogram. The generic term callable unit is sometimes used.

Wikipedia — Subroutine
Photo by Mousssss Liu on Unsplash

So subroutine is basically a function. I know functions! I don’t think it’s practically possible to learn programming without learning about functions anyway.


So linguistically, perhaps coroutines mean functions that can run and work together as an equal.

I’m happy with that conclusion. It’s something I can picture in my mind. It does not seem to explain technically all coroutines can do in the context of Kotlin programming, in fact it sounds a little too bland to me. However, it is concise and memorable. And that perhaps is all a good name needs to do.


Simple Way to Add a Global Constants File with Kotlin

One of the most common things I’m adding when making an Android app is a file that contains various constant values to be used in various places. Here’s how I’d set it up.

First, create the .kt file (usually I’d name it Constants.kt). Add the package name at the top, then add the constant variables without creating any class for them. In this example I assume that the file is on the root folder of the app. For example:

package studio.oldblack.wpflightcontrol
const val WPFC_SHARED_PREFS_FILENAME = "wpfc_prefs"
view raw constants.kt hosted with ❤ by GitHub
Gist containing the Constants.kt file example

Finally, to use the constants themselves, we can just write the name without any fuss (on line 2 on the example below):

val sharedPreferences = EncryptedSharedPreferences.create(
Example of how to use a constant variable