• Stars
    star
    145
  • Rank 254,144 (Top 6 %)
  • Language
    Kotlin
  • Created about 8 years ago
  • Updated about 7 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

🚀 How to use Kotlin with popular Android libraries

Getting started with Kotlin And third-party libraries Glide, Dagger 2, Retrofit 2, Realm, RxJava and MVP architecture on Android

Made in SteelKiwi Android Arsenal License

Read our new article here

It’s not a mystery to Android developers all over the world that the whole IT community has been trying to find a decent replacement for Java. Until 2011, before the Kotlin creation had been announced, Scala was the most suitable candidate. However, when JetBrains presented Kotlin programming language and its source code, it gradually became the strongest Java alternative in the field. This resulted in Kotlin becoming the official Android development language in 2017.

Kotlin was claimed to be a response to the massive amounts of code developers often had to write in Java and to Scala’s low-speed compilation. Today, many famous IT companies use Kotlin in their projects. The attention to this language is continuing to grow, as it wins over developers with its syntax and the fact that Kotlin is supported by several IDEs as a plugin. Even Jake Wharton, a recognized Android gospeller, uses Kotlin in his own projects, thus encouraging the whole Android community to use this language.

Let’s stay in tune with this trend and try Kotlin in practice to see its extensively debated pros and cons. Also, we will learn how to start developing Android applications in Kotlin.

What does Kotlin hide?

Mostly Kotlin is commended for its briefness and code safety and also for compatibility with Java and flexible usage. It’s hard to list all its advantages, so let’s consider the most interesting ones.

Strong sides of Kotlin:

  • It is Fully compatible with Java. It can use all available Java frameworks, libraries and also with separate modules in current projects.
  • It has open source code, so it’s easy to track and determine an issue and if you come up with it, you can always submit it to Kotlin developers.
  • Kotlins repository consumes less space than Scala, and adding Kotkin to a project is equal to Google library.
  • Starting from Java 6, it can use the major part of Java 7 and some portable elements of Java 8. That’s why it is easily available even if you are facing troubles updating to new JVM version.
  • There’s immutability by default.
  • It has Higher-Order Functions, i.e. the functions that take functions as parameters.
  • Null safety. Variables in Kotlin can’t possess the null value by default unless you denote them.
  • Kotlin became an officially supported language at the last Google IO conference (May 17th, 2017).

As for today, Kotlin isn’t very popular. The language is young and the community is yet to be formed. However, the ambitions for Kotlin are high. It has been under development for more than five years and the developers tried their best to avoid Java’s past mistakes. Java’s principle “Write Once Run Anywhere” doesn’t apply here as the language constantly changes and improves. Kotlin developers promise many interesting features, including the coverage of current Scala functionality.

With so many advantages, Kotlin almost seems to be the perfect programming language. However, it does also have some cons, even though they might not be as obvious.

WEAKNESSES OF KOTLIN:

  • Kotlin is Java 6 bytecode-oriented and doesn’t use a number of improvements available in Java 8 like invoke-dynamic.
  • There can appear issues with annotation processing.
  • There are no analogues to plugin-macros or compilers which thus limits the usage of convenient Scala macros or plugins like Checker Framework from Java.
  • If you practice joint usage of Java and Kotlin you need to follow certain rules of compatibility.
  • You will have to rewrite some proven to be effective solutions for Android, including the architectural ones as Kotlin enables the usage of alternative approach.
  • The language is pretty young and hasn’t found any specific niche, however, it is suitable not only for Android but also for backend development.
  • The language is pretty green and there are no worked out best practices for solving particular tasks.

Let’s dwell on compatibility and look closely at the example of a simple application development using such popular libraries like:

  • Glide - one of the most popular image loading libraries from Bump Technologies. Glide Library can upload and display images from many sources and manage cache, while also consuming small amount of internal memory for image processing.
  • Dagger 2 - the library developed by Google Inc. as a fast dependency injector for Android. It helps developers implement a Dependency Injection pattern which is “Inversion of control specific form”. Check out Kotlin + Dagger2 example below.
  • Retrofit 2 - a type-safe and the most popular HTTP client for Android Development. Kotlin and Retrofit libraries can be used in Android development without any drawbacks. Later we will show you a Kotlin Retrofit example.
  • Realm database. - a Mobile Database, which is an excellent substitute for SQLite and ORMs, as it operates faster, simpler and safer. The major part of Realm Kotlin library is written in Java. Our examples are below and you can check Realm Kotlin examples in the official Realm-java repository on GitHub.
  • RxJava + RxAndroid - Reactive programming has been deeply rooted in Mobile Development. Rx is a powerful tool that allows to solve issues in a neat declarative way of functional programming.There are thousands of articles telling about the benefits of RxJava, RxKotlin, RxAndroid and RxBinding for Android development. We won’t step aside and will use these libraries to work with asynchronous operations in a more convenient way. We will demonstrate you a small example of using Realm with RxJava in Kotlin.

The app serves as a good instance of libraries data usage and implementation of MVP architecture:

Screenshot

Let’s proceed to the development

It’s pretty easy to start the development process with Kotlin. First of all, you need to install the plugin:

Screenshot

After that configure your project. The easiest way to do this is to press Ctrl+Shift+A and find Configure Kotlin in Project item that will appear in autocomplete:

Screenshot

To convert existing Java classes to Kotlin you need to find the command named Convert Java to Kotlin:

Screenshot

Now let's start the integration of the needed libraries

Now let's start the integration of the needed libraries A few words before we start. Some libraries like Dagger 2 require Annotation Processing. Java Annotation Processing is not suitable for Kotlin. That’s why it includes its own Annotation Processing Tool for Kotlin (kapt), here is a great opinion on it.

To activate it you need to add this in the build.gradle file:

kapt {
    generateStubs = true
}
buildscript {
   ext.supportVersion = '25.0.0'
   ext.daggerVersion = '2.7'
   ext.retrofitVersion = '2.1.0'
   ext.rxVersion = '1.2.1'
   repositories {
       mavenCentral()
       jcenter()
   }
   dependencies {
       classpath "io.realm:realm-gradle-plugin:2.1.1"
   }
}


dependencies {
   compile fileTree(dir: 'libs', include: ['*.jar'])
   androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
       exclude group: 'com.android.support', module: 'support-annotations'
   })
   compile 'com.android.support:appcompat-v7:25.0.0'
   testCompile 'junit:junit:4.12'
   compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
   compile "com.android.support:cardview-v7:${supportVersion}"
   compile "com.android.support:design:${supportVersion}"


   // Dagger 2
   compile "com.google.dagger:dagger:${daggerVersion}"
   kapt "com.google.dagger:dagger-compiler:${daggerVersion}"
   provided "org.glassfish:javax.annotation:3.1.1"


   //Retrofit 2
   compile "com.squareup.retrofit2:retrofit:${retrofitVersion}"
   compile "com.squareup.retrofit2:adapter-rxjava:${retrofitVersion}"
   compile "com.squareup.retrofit2:converter-gson:${retrofitVersion}"


   compile 'com.google.code.gson:gson:2.8.0'


   compile "io.reactivex:rxjava:${rxVersion}"
   compile "io.reactivex:rxandroid:${rxVersion}"


   compile 'com.github.bumptech.glide:glide:3.7.0'


 }

Then we create inheriting class from Application and configure Realm and dependencies graph for Dagger 2 developed by Google:

class AppDelegate : Application() {


   var injector: AppInjector? = null


   @Singleton
   @Component(modules = arrayOf(NewsModule::class))
   interface AppInjector {
      
       fun inject(activity: MainActivity)
      
   }


   override fun onCreate() {
       super.onCreate()
       injector = DaggerAppDelegate_AppInjector.builder().build()


       Realm.init(this)
       val config = RealmConfiguration.Builder().build()
       Realm.setDefaultConfiguration(config)
   }
}

To work with HTTP we use Retrofit. We need to create an interface with one method that will receive news feed:

interface NewsApiInterface {
   @GET("/feeds/newsdefaultfeeds.cms?feedtype=sjson")
   fun getNews(): Observable<NewsResponse>
}

We create NewsModule class wherein the injected objectives will be created:

@Module
class NewsModule {


   @Provides
   @Singleton
   fun provideNewsPresenter(): NewsPresenter {
       return NewsPresenter()
   }


   @Provides
   @Singleton
   internal fun provideNewApiInterface(): NewsApiInterface {
       val retrofit = Retrofit.Builder()
               .baseUrl(Constants.NEWS_ENDPOINT)
               .addConverterFactory(GsonConverterFactory.create())
               .addCallAdapterFactory(RxJavaCallAdapterFactory.createWithScheduler(Schedulers.io()))
               .build()
       return retrofit.create(NewsApiInterface::class.java)
   }
}

In NewsPresenter class we will use RxAndroid and Realm for news feed processing and caching :

subscription = mNewsApiInterface!!
       .getNews()
       .map { it.newsItem }
       .flatMap({ items ->
           Realm.getDefaultInstance().executeTransaction({ realm ->
               realm.delete(NewsItem::class.java)
               realm.insert(items)
           })
           Observable.just(items)
       })
       .onErrorResumeNext { throwable ->
           val realm = Realm.getDefaultInstance()
           val items = realm.where(NewsItem::class.java).findAll()
           Observable.just(realm.copyFromRealm(items))
       }
       .observeOn(AndroidSchedulers.mainThread())
       .doOnTerminate { mNewsView?.hideLoading() }
       .subscribe({ mNewsView?.onNewsItemLoaded(it) }, { mNewsView?.onError(it) })

Projects source code is available on this Repository =)

Let’s sum up

All in all, Kotlin is a modern and secure programming language that simplifies Android apps development. It looks like a distinct alternative to Java as it has good documentation and it is simple enough for understanding. We hope that this article helped you to figure out how to create a project on Kotlin and integrate the needed libraries.

License

The MIT License (MIT)

Copyright © 2017 SteelKiwi, http://steelkiwi.com

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

More Repositories

1

cropiwa

📐 Configurable Custom Crop widget for Android
Java
2,228
star
2

AndroidRecording

Android Recording library offers convenient tools for audio/video recording and playback
Java
418
star
3

IncrementProductView

Interesting concept of products incrementation
Java
259
star
4

SeparateShapesView

Simple custom ViewGroup with two shapes inside and simple scale animation
Java
248
star
5

SlidingSquareLoaderView

Marvelous sliding square loader view
Kotlin
179
star
6

BadgeHolderView

ViewGroup for browse badge view with count of some products
Java
66
star
7

DotsLoaderView

Simple dots loader view
Java
66
star
8

aiohttp_test_chat

Simple aiohttp test chat
Python
58
star
9

django-skd-smoke

This package is intended for simplification of smoke tests creation
Python
48
star
10

libGDX-Path-Editor

libGDX Path Editor lets you easily create complex pathes your game characters can move along.
Java
44
star
11

locust-bokeh-load-test

Python
41
star
12

IndicatorView

Configurable view for ViewPager
Java
40
star
13

jwt-python-tutorial

Example repo for JWT in Python tutorial
Python
25
star
14

VideoFramingDemo

This is a simple demo which works with Android's MediaMetadataRetriever class to extract frames from video file
Java
22
star
15

ListView-Swipe-to-Delete

ListView Swipe to Delete is an Android library which offers a list view navigation mode similar to Any.do application
Java
20
star
16

CenteredContentButton

Centered Content Button is Android library which contains button-like and toggle button-like components with centered content - icon and/or text.
Java
16
star
17

ErrorLayout

Simple layout to show custom error toast with animation
Java
13
star
18

collection_in_kotlin

📖 Collections in Kotlin for Android developers
Kotlin
13
star
19

SketchView

SketchView library provides a custom implementation of a canvas on which user can draw via gestures
Java
13
star
20

django-skd-tools

Python
11
star
21

PullRefreshLayout

Simple custom view pull to refresh
Java
9
star
22

SKLocalizable

Localization add-on for native iOS components
Swift
8
star
23

django-template

Python
8
star
24

django-singleton-tutorial

Example repo for Singleton model in Django tutorial. http://steelkiwi.com/blog/practical-application-singleton-design-pattern/
Python
7
star
25

ErrorParser

Simple JSON parser for Android
Java
7
star
26

django_aiohttp_websockets

Example Django-project with Websocket's chat written using aioHTTP and aioRedis
Python
6
star
27

Android-Image-Worker-Library

Android library that helps you downloading and storing images.
Java
6
star
28

SKExtensions

Common used Extensions in Swift
Swift
5
star
29

NavigationTools

Java
4
star
30

emacs.d

Emacs configuration for working with Python
Emacs Lisp
4
star
31

SoundCloudAuthentificator

Swift
3
star
32

django-steelkiwi-project

project template
Python
3
star
33

hunting-kiwi

🔫 Simple ERP system for HR managers
JavaScript
2
star
34

exchange_rates

Crypto currencies exchange rates flutter redux sample project for uamobile 2019
Dart
2
star
35

ErrorParse-ios

Parser class for error text retrieving
Swift
2
star
36

js-helpers

JavaScript
2
star
37

angular1-boilerplate

Boilerplate for Angular 1 on es6-modules
JavaScript
2
star
38

spa-battle

Small SPA implemented with most popular front-end frameworks
HTML
2
star
39

SKChart

Swift
1
star
40

AppDelegate-Firebase

Example of using Firebase PushMessages in iOS
Swift
1
star
41

django-knowledge

Python
1
star