5. Kotlin for Android
● Reduce the amount of boilerplate code you need to write
● Make your code more readable and understandable
● No more errors such as NPE
● No more findViewById()
● One language for Android & Gradle
● Interoperability
● New languge -> Kotlin is fun
● Compatible with JDK 6 -> can run on older Android devices
6. Kotlin for Android / Android Extensions
Kotlin Android Extensions
● Compiler extension that allows to us replace findViewById() calls with
synthetic-generated properties
13. Anko
● Anko is a library that uses Kotlin and provides a lot of extension functions to
make our Android development easier.
● It contains wrappers around the Android APIs and DSL that allows to us to
replace layouts written in the XML file
14. Anko
Gradle
dependencies {
// Anko
compile "org.jetbrains.anko:anko-sdk15:$anko_version"
compile "org.jetbrains.anko:anko-support-v4:$anko_version"
compile "org.jetbrains.anko:anko-appcompat-v7:$anko_version"
}
15. Anko - Layouts
val act = this
val layout = LinearLayout(act)
layout.orientation = LinearLayout.VERTICAL
val name = EditText(act)
val button = Button(act)
button.text = "Say Hello"
button.setOnClickListener {
Toast.makeText(act, "Hello, ${name.text}!",
Toast.LENGTH_SHORT).show()
}
layout.addView(name)
layout.addView(button)
verticalLayout {
val name = editText()
button("Say Hello") {
onClick { toast("Hello, ${name.text}!") }
}
}
20. Anko - Buttons and Toasts
With Kotlin we can add click listener and show toast like this:
buttonNext.setOnClickListener {
Toast.makeText(baseContext, "CLicked!!", Toast.LENGTH_LONG).show;
}
21. Anko - Buttons and Toasts
With Kotlin we can add click listener and show toast like this:
but with Anko we can do it better:
buttonNext.setOnClickListener {
Toast.makeText(baseContext, "CLicked!!", Toast.LENGTH_LONG).show;
}
buttonNext {
onClick {
toast("Hello ${username.text}")
}
}
or we can show LONG toast:
onClick { longToast("Hello ${username.text}") }
22. Anko - Asynchronous Tasks
fun authorizeUser(username: String, password: String) {
doAsync {
val authorized = signInBL.checkUserCredentials(AuthCredentials(username = username, password = password))
activityUiThread {
if (authorized) toast("Signed!!!") else view.showAccessDeniedAlertDialog()
}
}
}
23. Anko - Asynchronous Tasks
Since Anko 0.10-beta1 a new way Anko Coroutines
dependencies {
compile "org.jetbrains.anko:anko-coroutines:$anko_version"
}
24. Anko - Asynchronous Tasks
Since Anko 0.10-beta1 a new way Anko Coroutines suspend fun getData(): Data { ... }
class MyActivity : Activity() {
fun loadAndShowData() {
// Ref<T> uses the WeakReference under the hood
val ref: Ref<MyActivity> = this.asReference()
async(UI) {
val data = getData()
// Use ref() instead of this@MyActivity
ref().showData()
}
}
fun showData(data: Data) { ... }
}
25. Anko - Asynchronous Tasks
Since Anko 0.10-beta1 a new way Anko Coroutines fun getData(): Data { ... }
fun showData(data: Data) { ... }
async(UI) {
val data: Deferred<Data> = bg {
// Runs in background
getData()
}
// This code is executed on the UI thread
showData(data.await())
}
https://github.com/Kotlin/anko/wiki/Anko-Coroutines
27. Anko - Intents
Anko contains some useful wrappers for some common intents:
// Took it from original Anko documentation
// Make a call
makeCall(number) // Intent(Intent.ACTION_CALL, Uri.parse("tel:$number"))
// startActivity(intent)
// Send a text
sendSMS(number, [text])
//Browse the web
browse(url)
//Share some text
share(text, [subject])
//Send a email
email(email, [subject], [text])
Arguments in square brackets ([]) are optional
28. Anko - Intents
Start a new activity
val intent = Intent(this, SomeOtherActivity::class.java)
intent.putExtra("id", 5)
intent.setFlag(Intent.FLAG_ACTIVITY_SINGLE_TOP)
startActivity(intent)
29. Anko - Intents
Start a new activity
with Anko:
val intent = Intent(this, SomeOtherActivity::class.java)
intent.putExtra("id", 5)
intent.setFlag(Intent.FLAG_ACTIVITY_SINGLE_TOP)
startActivity(intent)
startActivity(intentFor<SomeOtherActivity>("id" to 5).singleTop())
startActivity<SomeOtherActivity>("id" to 5)
30. Anko - Logging
class SomeActivity : Activity(), AnkoLogger {
private fun someMethod() {
info("Prague is the capital of Czech Republic")
debug(5) // .toString() method will be executed
warn(null) // "null" will be printed
}
}
…..
info { "Prague is the capital of Czech Republic" }
31. Anko
● Anko SQLite
○ Provides lots of extension functions to simplify working with SQLite
dependencies {
compile
"org.jetbrains.anko:anko-sqlite:$anko_version"
}
class MySqliteOpenHelper : ManagedSQLiteOpenHelper {}
database.use {
// Here we have SQL
}
32. Anko
● Anko SQLite
○ Provides lots of extension functions to simplify working with SQLite
val values = ContentValues()
values.put("id", 1)
values.put("name", "Vaclav")
values.put("email", "vaclav@email.com")
db.insert("User", null, values)
db.insert("User",
"id" to 1,
"name" to "Vaclav",
"email" to "vaclav@email.com"
)
33. Anko
● Anko SQLite
○ Provides lots of extension functions to simplify working with SQLite
db.select("User", "name")
.whereArgs("(_id > {userId}) and (name = {userName})",
"userName" to "John",
"userId" to 42)
https://github.com/Kotlin/anko/wiki/Anko-SQLite
34. Modern SQL based query & persistance for Java / Kotlin / Android
https://github.com/requery/requery
35. Requery
● Object mapping and SQL generator for Java/Kotlin/Android
○ RxJava and Java 8 support
○ Create databases
○ Perform queries and updates
36. Requery
● Features
○ No Reflection
○ Typed query language
○ Table generation
○ Supports JDBC and most popular databases (MySQL, Oracle, SQL
Server, Postgres and more)
66. KotlinPref
Android SharedPreferences delegation library for Kotlin
object UserInfoPrefModel : KotprefModel() {
var userId: Int by intPrefVar(default = -1)
var name: String by stringPrefVar()
}
Live Demo
https://github.com/chibatching/Kotpref