ProAndroidDev

The latest posts from Android Professionals and Google Developer Experts.

Follow publication

Android Jetpack Series with Goku: Android X and KTX

You must have remembered when Goku becomes a great ape and his friends have to solve that problem permanently. After which Goku started training under Master Roshi to become more powerful than anyone else. We are going to do the same in this article.

You can check out the intro of this series here.

Nowadays, whenever we start a new project on Android Studio it comes up with some predefined dependencies where we can see a new word, mostly two years old “androidx”. Just like the below code:

implementation "androidx.appcompat:appcompat:$app_compat_version"

In this article, we are going to see from where does this AndroidX came from. Then we will see what KTX in Android is and how we can use all these things and make our development easy.

What is AndroidX?

It is really hard to manage when Goku grows to a great ape, attacking the weak point, Goku’s Tail, had solved this problem permanently.

Similarly, In the old days, it's very hard for Android Developers to manage such a bunch of libraries/dependencies in their project. So, just like Goku friends, our Android Friends attack the weak point and had removed all those so-called v4, v13…..

Android Extensions (AndroidX) is a library itself, a redesigned library. All the android classes come with an operating system and all other it’s libraries are upgraded to AndroidX and all the new upcoming libraries will be the part of it.

Let’s go back in history!!!

Earlier days people use libraries called support library which Google has developed back in 2011 with Android Honeycomb release. That was the time when fragment first showed up in those libraries. Those libraries look like

v4 means minimum API level is 4
v4 Support Library
-> Android 1.6, 2.3 and 4.0 and higher

v7 means minimum API level is 7
v7 Support Library
-> Android 2.1, 2.3, and 4.0 and higher

v13 means minimum API level is 13
v13 Support Library
-> Android 3.2 and higher

All these increases the naming issues and updating the libraries on the project is also becoming difficult day by day. Also, Gradle warns to keep all libraries version at the same level, which is hard to maintain and because of that we had to update the library unnecessarily. So, they had come up with the new library following the set of rules called strict semantic versioning. This rule says the version name consists of three things:

MAJOR.MINOR.PATCH starting with 1.0.0

This new journey started with AndroidX after support library revision has no more v4, v7, v13 or anything extra.

28.0.0 → 1.0.0

Today, before releasing any library to stable, Google has three pre-release stages. Alpha, Beta and RC. And today we have AndroidX libraries. You can check all libraries release here.

This is what AndroidX is, all set of new and upgraded libraries.

As we all know Google had already announced Kotlin as an official language for Android back in 2017. And with this, they had come up with an extension to bring more power to this language and make the development super easy. Let’s see what are these extensions…

What is Android KTX?

It’s very important to harness the power of all our tools and also add new tools to our set. Master Roshi, once had given a flying nimbus to Goku as a present to complete all task as fast as he can.

Similarly, Google has added Kotlin as a new tool in our set and now we have to harness its power to use it at max. AndroidKTX is a set of extensions which can harness the power of Kotlin language features for Android App Development. KTX is a part of Jetpack and it is divided into modules. Android KTX has one core module and a few other modules which are more domain-specific. Today, most of the developers are shifted on Kotlin and if you are not, then reading this article will help you understand what are the things you are missing in your developer journey.

We will be understanding Android KTX in two parts:

  1. What kotlin features do these extensions take advantage of?
  2. Android KTX modules

Kotlin features

Extension functions — extending pre-defined functions, not inheriting them and adding more functionality to it makes your functions known as an extension function.

Extension properties — Just like extension functions, we have extension properties, data inside a function can be modified and makes it easy to use. The only thing we have to keep in mind while working with extension properties is that it cannot save the state, but will need to use existing functions to request or modify the state of the object. This revokes use of initializers.

Lambdas — no name function, these can be passed as an expression without declaring it.

we can implement the same using lambda, this also makes the code less

Named parameters — There are situations when we need to pass lots of arguments to a function. Sometimes, it is possible that we jumble or miss any arguments, and this leads to the error and we had to check the implementation of that function and correct it. With this named parameters now we can pass arguments using the parameters name, no need to pass arguments in the correct order.

passValue(senzuPill = 5, dragonBall = 7)

Parameter default values — Sometimes, we had to pass lots of arguments and this eventually increases the development time. Now, with the default values of parameters, we don’t need to pass the argument if the default value satisfies our conditions. We can simply skip the parameters whose default values we want to use.

Coroutines — Working with multiple threads is always hard to manage and increases the development time as well. Either we need to put some delay or make a network connection or a database query, we always need to do work in an asynchronous way. Coroutines simply take our work to another thread and get it done while the user is busy on the main thread either watching an amazing loading animation or interacting with other components.

Android KTX module

Below is the list of modules and we will see the core module in more details

Core KTX

Collection KTX

Fragment KTX

Lifecycle KTX

LiveData KTX

Navigation KTX

Palette KTX

Reactive Streams KTX

Room KTX

SQLite KTX

ViewModel KTX

WorkManager KTX

Let’s see how to use these modules

Core KTX

Core KTX provided an extension for common libraries of android. Below is the list of packages under it

✪ Animation — androidx.core.animation

Working on animations becomes easy with KTX. Simply use underline methods leveraging the power from kotlin features

✪ Content — androidx.core.content

Content helps us to access system services or work with shared pref

✪ Resource — androidx.core.content.res

With resource, we can access our defined resource in the res folder and also configurations

✪ Database — androidx.core.database

This extension helps us to work with cursor

cursor.getIntOrNull(index = 0)

✪ SQLite — androidx.core.database.sqlite

Only one extension is provided, helps us to do the transaction

sqLiteDatabaseObject.transaction { }

✪ Graphics — androidx.core.graphics

Makes it easy with working on bitmaps, colour utils, Paint compat

val drawable = someInt.toDrawable()

✪ Drawable — androidx.core.graphics.drawable

Work on drawable with KTX

val bitmap = someInt.toBitmap()

✪ Location — androidx.core.location

Currently, under this package, there are only two methods which return latitude and longitude

✪ Network Connectivity — androidx.core.net

✪ OS — androidx.core.os

Accessing the os level classes. Currently, it has two methods to get the runnable

✪ Text — androidx.core.text

Text is one of the major developers work most with to modify at their level. KTX brings all those boilerplate codes to end

SpannableStringBuilder.backgroundColor(color = R.color.green) { 
// builder action
}

✪ Transition — androidx.core.transition

Just like animations, transition providers method to work on the go

✪ Util — androidx.core.util

Util has a collection of the file where we can work with AtomicFile, Pair, Range and much more

✪ View — androidx.core.view

Access the inner methods of View

View.drawToBitmap()
View.setPadding()

✪ Widget — androidx.core.widget

Currently, we can work with TextView

Collection KTX

To use Android’s collection utility functions, use collection KTX which gives more things to use like ArrayMap, LongParseArray, LruCache. Taking advantage of Kotlin’s operator overloading.

val combinedArraySet = arraySetOf(1, 2, 3) + arraySetOf(4, 5, 6)

Fragment KTX

With fragment KTX, working on fragment becomes simple with less code. Transaction on fragment requires a lot of lines of code but with KTX it’s just a kotlin lambda.

Also, now bind View Model in just one line.

val viewModel by activityViewModels<MyViewModel>()

Lifecycle KTX

This provides the lifecycleScope, making the use of coroutine with the lifecycle.

viewLifecycleOwner.lifecycleScope.launch { }

LiveData KTX

Working with live data sometimes require some asynchronous work. This provides a LiveData builder function.

Navigation KTX

Here, Kotlin’s extension function and delegation property work to lessen the code.

Palette KTX

Simplify the use of colours

val palette = Palette.from(bitmap).generate()

Reactive Streams KTX

Create an observable LiveData stream from a ReactiveStreams publisher.

Room KTX

Room extension helps with coroutine to work faster and easy

SQLite KTX

As discussed earlier in this article, it has one extension

db.transaction { }

ViewModel KTX

Brings the power of coroutine to view model. With this KTX we have ViewModelScope, this will automatically clear when onCleared() is called.

viewModelScope.launch  { }

WorkManager KTX

This KTX supports coroutine

Goku had experienced his first Kamehameha. So do we, our power of X and KTX.

Conclusion

You have read about what AndroidX is and how it comes to picture. What Android KTX is and how it is useful to us. Use this learning in your project and bring your Android code to diet.

In the next upcoming article, we are going to see under the hood implementation and need of LiveData, ViewModel, Lifecycle and DataBinding libraries. Also, we have CameraX, WorkManager, Navigation, Paging, Notifications and much more in this series upcoming.

Thanks for reading! If you enjoyed this story, please click the 👏 button and share to help others find it! Feel free to leave a comment 💬 below.
Have feedback? Let’s be friends ->
Twitter, Instagram, or my profile

Published in ProAndroidDev

The latest posts from Android Professionals and Google Developer Experts.

Written by Akshay Nandwana

Working with United Nations and Google Team • Ex-Software Engineer @Google @Zee5 @Doubtnut • Ex-GDSC Lead • Ex-GSoC Mentor • Android Engineer • 10M+ Impressions

No responses yet

Write a response