Companion App for the book

Overview

Kotlin for Android Developers (the book)

This is the code you can use to follow the book.

https://antonioleiva.com/kotlin-android-developers-book/

Are you tired of using an ancient, inexpressive and unsafe language to develop your Android apps? Do you cry out loud every time you see a Null Pointer Exception in your bug tracker? Then Kotlin is your solution! A language specifically created for Java developers, easy to learn, expressive, null safe and really intuitive. Your productivity will boost and your apps will become more robust. Learn Kotlin the easy way by example and discover the tricks that will make coding easier.

And now, it's officially supported by Google!

Kotlin for Android Developers cover

About the book

In this book, I'll be creating an Android app from ground using Kotlin as the main language. The idea is to learn the language by example, instead of following a typical structure. I'll be stopping to explain the most interesting concepts and ideas about Kotlin, comparing it with Java 7. This way, you can see what the differences are and which parts of the language will help you speed up your work.

This book is not meant to be a language reference, but a tool for Android developers to learn Kotlin and be able to continue with their own projects by themselves. I'll be solving many of the typical problems we have to face in our daily lives by making use of the language expressiveness and some other really interesting tools and libraries.

The book is very practical, so it is recommended to follow the examples and the code in front of a computer and try everything it's suggested. You could, however, take a first read to get a broad idea and then dive into practice.

Versions

As I update the book, I need to push -f this repository with the new changes, so that it matches with the new text.

That means that if you are reading an old version of the book, main branches won't be aligned with your text.

To make things easier, I'll keep track of those versions in separates branches, which will be linked from here:

License

Copyright 2019 Antonio Leiva

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Comments
  • Book Errata: 7.2 Start using Anko

    Book Errata: 7.2 Start using Anko

    The following code sample does not work anymore: val forecastList: RecyclerView = find(R.id.forecast_list)

    Use this instead: val forecastList = find<RecyclerView>(R.id.forecast_list)

    opened by bytehala 5
  • Chapter 19 does not compile

    Chapter 19 does not compile

    I have been following along in the book. When I added the code for Chapter 19, the DatabaseExtensions.kt file will not compile. To ensure that I didn't type something wrong, I got a zip of the Chapter 19 commit and got the same error:

    • Error:(8, 19) Object must be declared abstract or implement abstract member public abstract fun parseRow(columns: Map<String, Any?>): T defined in org.jetbrains.anko.db.MapRowParser
    • Error:(9, 13) 'parseRow' overrides nothing
    • Error:(13, 18) Object must be declared abstract or implement abstract member public abstract fun parseRow(columns: Map<String, Any?>): T defined in org.jetbrains.anko.db.MapRowParser
    • Error:(14, 13) 'parseRow' overrides nothing

    I'm using buildVersonSdk 25.0.0, targetSdkVersion 25, ext.support_version 25.1.0, ext.kotlin_version 1.0.6, ext_anko_version 0.9 in Android Studio. Everything had worked up to the transition from earlier chapters to chapter 19. Since I'm new to Kotlin, I don't have a clue what is wrong or how to fix it.

    opened by NoRefill 5
  • Create SqlLite table failed when running the app

    Create SqlLite table failed when running the app

    When I run the app, an error was occurred by create database table DayForecastTable. This is the error: android.database.sqlite.SQLiteException: near "org": syntax error (code 1): , while compiling: CREATE TABLE IF NOT EXISTS DayForecast(id INTEGER PRIMARY KEY org.jetbrains.anko.db.SqlTypeModifierImpl@a5038ce, date INTEGER, description TEXT, high INTEGER, low INTEGER, iconUrl TEXT, cityId INTEGER); Why the AUTOINCREMENT cannot be recognized. My anko version is 0.10.1

    opened by wangjinzhong 4
  • Change http links to https-- Android error

    Change http links to https-- Android error

    In MainActivity.kt, starting with Chapter 8, the http link gives me this error in MainActivity->onCreate:

    weatherapp W/System.err: java.io.IOException: Cleartext HTTP traffic to api.openweathermap.org not permitted

    I propose changing the http://api.openweather... URL to https://api.openweather...

    opened by RyanDurk 3
  • zip code vs city id in chapter-19 branch

    zip code vs city id in chapter-19 branch

    In the chapter-19 branch there is a mix-up between zip code and city id. The code compiles and runs because the database is not used. Nonetheless I believe there is an error. Here is what I think needs to change:

    In ForecastDataMapper.convertFromDataModel the first parameter in the ForecastList constructor should be "city.id" instead of "zipCode". Additionally, the "zipCode" parameter should be removed from convertFromDataModel so that it takes only a ForecastResult.

    Once this change is made the overridden function in RequestForecastCommand must be changed so the "zipCode" parameter is removed from the parameters passed to convertFromDataModel.

    This will fix the issue, but I would also recommend changing the name of the "id" parameter on the ForecastList constructor to "cityId" to make it clearer what id this is.

    opened by bartonstanley 3
  • todayTimeSpan() does not account for time zone, but OpenWeatherMap API does

    todayTimeSpan() does not account for time zone, but OpenWeatherMap API does

    This becomes a problem when the date of your time zone differs from the date of GMT time.

    1. ForecastByZipCodeRequest obtains a weekly forecast starting with today in your current time zone.
    2. ForecastDb.requestForecastByZipCode(zipCode, todayTimeSpan()) filters out the first row of DayForecastTable because its column DATE precedes todayTimeSpan().
    3. ForecastProvider.requestByZipCode(zipCode, days) never returns a non-null value.

    I am in America/New York (EDT GMT -04:00 DST) time zone. Here is a real example when I run the app:

    • System.currentTimeMillis() is 1464056054644, or May 23, 2016 at 10:14:14 PM EDT GMT-4:00 DST
    • todayTimeSpan() is 1464048000000, or May 23, 2016 at 8:00:00 PM EDT GMT-4:00 DST
    • Date values for returned by OpenWeatherMap for seven-day forecast are: {1464001200000, 1464087600000, 1464174000000, 1464260400000, 1464346800000, 1464433200000, 1464519600000}
    • Database only returns {1464087600000, 1464174000000, 1464260400000, 1464346800000, 1464433200000, 1464519600000}
    opened by alan-rodriguez 3
  • Anko for RecyclerView

    Anko for RecyclerView

    Can't we use Anko for the RecyclerView here?:

    https://github.com/antoniolg/Kotlin-for-Android-Developers/blob/master/app/src/main/java/com/antonioleiva/weatherapp/activities/MainActivity.kt#L28

    opened by amouly 3
  • Chapter 8 Code example doesn't run as described

    Chapter 8 Code example doesn't run as described

    Running the code from Chapter 8 branch, the toast never actually occurs. This is the error log I see in Logcat:

    11-19 16:57:50.053 5203-5203/? I/zygote: Not late-enabling -Xcheck:jni (already on) 11-19 16:57:50.064 5203-5203/? W/zygote: Unexpected CPU variant for X86 using defaults: x86 11-19 16:57:50.275 5203-5203/com.antonioleiva.weatherapp I/InstantRun: starting instant run server: is main process 11-19 16:57:50.462 5203-5229/com.antonioleiva.weatherapp D/NetworkSecurityConfig: No Network Security Config specified, using platform default 11-19 16:57:50.489 5203-5231/com.antonioleiva.weatherapp D/OpenGLRenderer: HWUI GL Pipeline

                                                                           [ 11-19 16:57:50.541  1902: 2245 W/         ]
                                                                           Unrecognized GLES max version string in extensions: ANDROID_EMU_CHECKSUM_HELPER_v1 ANDROID_EMU_dma_v1 
    

    11-19 16:57:50.545 5203-5229/com.antonioleiva.weatherapp W/System.err: java.io.FileNotFoundException: http://api.openweathermap.org/data/2.5/forecast/daily?APPID=15646a06818f61f7b8d7823ca833e1ce&q=94043&mode=json&units=metric&cnt=7 11-19 16:57:50.546 5203-5229/com.antonioleiva.weatherapp W/System.err: at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:251) 11-19 16:57:50.551 5203-5229/com.antonioleiva.weatherapp W/System.err: at java.net.URL.openStream(URL.java:1058) 11-19 16:57:50.553 5203-5229/com.antonioleiva.weatherapp W/System.err: at kotlin.io.TextStreamsKt.readBytes(ReadWrite.kt:144) 11-19 16:57:50.562 5203-5229/com.antonioleiva.weatherapp W/System.err: at com.antonioleiva.weatherapp.data.Request.run(Request.kt:9) 11-19 16:57:50.563 5203-5229/com.antonioleiva.weatherapp W/System.err: at com.antonioleiva.weatherapp.ui.activities.MainActivity$onCreate$1.invoke(MainActivity.kt:39) 11-19 16:57:50.563 5203-5229/com.antonioleiva.weatherapp W/System.err: at com.antonioleiva.weatherapp.ui.activities.MainActivity$onCreate$1.invoke(MainActivity.kt:15) 11-19 16:57:50.563 5203-5229/com.antonioleiva.weatherapp W/System.err: at org.jetbrains.anko.AsyncKt$doAsync$1.invoke(Async.kt:140) 11-19 16:57:50.569 5203-5229/com.antonioleiva.weatherapp W/System.err: at org.jetbrains.anko.AsyncKt$doAsync$1.invoke(Unknown Source:0) 11-19 16:57:50.570 5203-5229/com.antonioleiva.weatherapp W/System.err: at org.jetbrains.anko.AsyncKt$sam$Callable$761a5578.call(Unknown Source:2) 11-19 16:57:50.570 5203-5229/com.antonioleiva.weatherapp W/System.err: at java.util.concurrent.FutureTask.run(FutureTask.java:266) 11-19 16:57:50.571 5203-5229/com.antonioleiva.weatherapp W/System.err: at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:301) 11-19 16:57:50.572 5203-5229/com.antonioleiva.weatherapp W/System.err: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162) 11-19 16:57:50.573 5203-5229/com.antonioleiva.weatherapp W/System.err: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636) 11-19 16:57:50.574 5203-5229/com.antonioleiva.weatherapp W/System.err: at java.lang.Thread.run(Thread.java:764) 11-19 16:57:51.029 5203-5231/com.antonioleiva.weatherapp I/OpenGLRenderer: Initialized EGL, version 1.4 11-19 16:57:51.029 5203-5231/com.antonioleiva.weatherapp D/OpenGLRenderer: Swap behavior 1 11-19 16:57:51.030 5203-5231/com.antonioleiva.weatherapp W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without... 11-19 16:57:51.030 5203-5231/com.antonioleiva.weatherapp D/OpenGLRenderer: Swap behavior 0 11-19 16:57:51.032 5203-5231/com.antonioleiva.weatherapp D/EGL_emulation: eglCreateContext: 0xa73850c0: maj 2 min 0 rcv 2 11-19 16:57:51.035 5203-5231/com.antonioleiva.weatherapp D/EGL_emulation: eglMakeCurrent: 0xa73850c0: ver 2 0 (tinfo 0xa73832a0)

                                                                          [ 11-19 16:57:51.038  1902: 1911 W/         ]
                                                                          Unrecognized GLES max version string in extensions: ANDROID_EMU_CHECKSUM_HELPER_v1 ANDROID_EMU_dma_v1 
    

    11-19 16:57:51.063 5203-5231/com.antonioleiva.weatherapp D/EGL_emulation: eglMakeCurrent: 0xa73850c0: ver 2 0 (tinfo 0xa73832a0)

    opened by abunur 2
  • errors importing in androdiStudio3 preview2

    errors importing in androdiStudio3 preview2

    importing this demo app in the last canary Android Studio, I found some errors during the sync.

    please modify the code of "app" like:

        compile "org.jetbrains.anko:anko:0.10.1"
        compile "org.jetbrains.anko:anko-common:0.10.1"
        compile "org.jetbrains.anko:anko-sqlite:0.10.1n"
        compile "org.jetbrains.anko:anko-coroutines:0.10.1"
    
    

    this is enounght to fix the errors of sync

    regards MaX

    opened by maxlinux2000 2
  • Screen Is Empty After Fetching Weather Information

    Screen Is Empty After Fetching Weather Information

    Okay. So, I started with the tutorial and everything has been going on fine not until I got to chapter 10 trying to implement the Asyn.

     doAsync {
            val result = RequestForecastCommand("94043").execute()
            Log.e(javaClass.simpleName, result.toString()) <-- It doesn't get to this place at all
            uiThread() {
                Log.e(TAG, "I am here")
                Log.e(javaClass.simpleName, result.toString())
                forcast_list.adapter = ForcastListAdapter(result)
            }
        }
    

    Then, I debugged further and checked the ForecastRequest.kt file

     class ForecastRequest(val zipCode: String) {
    
    companion object {
        private val APP_ID = "15646a06818f61f7b8d7823ca833e1ce"
        private val URL = "http://api.openweathermap.org/data/2.5/" +
                "forecast/daily?mode=json&units=metric&cnt=7"
        private val COMPLETE_URL = "$URL&APPID=$APP_ID&q="
    }
    
    fun execute(): ForecastResult {
        val forcastJsonStr = URL(COMPLETE_URL + zipCode).readText()
        Log.e(javaClass.simpleName, forcastJsonStr)<-- This printed out a result
        return Gson().fromJson(forcastJsonStr, ForecastResult::class.java)
    }
    }
    

    I don't know why it's not throwing any error or any bug though. And should it be a Gson conversion error, at least I'm supposed to get an error right?

    opened by tonespy 2
  • ServerClasses, gson and null properties

    ServerClasses, gson and null properties

    I have a doubt about the data classes in ServerClasses.tk. This classes are popullated using GSon. When Gson creates the classes it will use a kind of empty constructor and it will fill the properties, therefore, there might be values that are null (in case the api changes for example). Shouldn't we put default values ensure no null properties?

    opened by mateuy-dev 1
  • Anko is a deprecated library

    Anko is a deprecated library

    Hi i see that you use Anko lib, but i recently read that it is a deprecated library:

    https://github.com/Kotlin/anko/blob/master/GOODBYE.md

    Have you planned to remove this lib and update your code?

    opened by billyjoker 0
  • Compilation error

    Compilation error

    https://github.com/antoniolg/Kotlin-for-Android-Developers/blob/c72118e411a9462a37370c1f53a31fc63fe6748b/app/src/main/java/com/antonioleiva/weatherapp/data/db/DbDataMapper.kt#L9

    Where does the id come from?

    opened by LiviuSo 6
Owner
Antonio Leiva
Freelance trainer. I help you and your company to become Kotlin experts. GDE and Jetbrains Training Partner.
Antonio Leiva
This is a practice app. An app that you can find random recipes and choose the ones you like.

A food suggestion app like Tinder This is a practice app. In this app, you can find random recipes and choose the ones you like. This is main menu. Yo

Yunus Emre OCAK 4 May 25, 2022
To help to promote your android app by prompting users to rate your app in a bottom Sheet.

RateBottomSheet This an Android library to help to promote your Android App by prompting users to rate your app in the Google Play Store with a materi

Farham Hosseini 5 Jul 8, 2022
New style for app design Online Sunglasses Shop App UI made in Jetpack Compose.😉😎

JetSunglassUI-Android New style for app design Online Sunglasses Shop App UI made in Jetpack Compose. ?? ?? (Navigation Components, Dagger-Hilt, Mater

Arvind Meshram 18 Dec 12, 2022
A sample skeleton backend app built using Spring Boot kotlin, Expedia Kotlin Graphql, Reactive Web that can be deployed to Google App Engine Flexible environmennt

spring-kotlin-gql-gae This is a sample skeleton of a backend app that was built using: Spring Boot(Kotlin) Reactive Web Sprinng Data R2DBC with MYSQL

Dario Mungoi 7 Sep 17, 2022
These files are included in an Android Studio Project for a Magic the Gathering Life Counter app. The app was written in Kotlin.

Magic-Life-Counter These files were created in Android Studio using Kotlin. Usage This app was made to keep track of life totals while playing the tra

null 0 Dec 24, 2021
Relationship-app-android - An app with features aimed towards me and my girlfriend

RelationshipApp Android An Android app with features aimed towards me and my gir

Rostislav Osvald 0 Jan 3, 2022
Explore-KiiT-App - An app to simplify the complicated website navigation and keep track of Attendance

KiiT Explore App "An app to simplify the complicated website navigation and keep

Ajay Khatri 17 Oct 12, 2022
App with plant list 🌱 , the app reminds you when to water 💦 your best plant at a certain time.

Plant Life App with plant list ?? , the app reminds you when to water ?? your best plant at a certain time.. Table of Contents Introduction Features U

Haya Saud Alrawdhan 0 Jan 6, 2022
Swarup 2 Feb 6, 2022
Tictactoe-android-app - Simple TicTacToe Android app written in Kotlin

TicTacToe Android App This is a simple example of TicTacToe game as Android app

Blaž Čerpnjak 1 Jul 9, 2022
Android Note app that uses the "ktor-note-app" backend

KtorNoteApp Android Notes app that uses Ktor back end server Technologies employed: Kotlin MVVM Coroutines Custom REST API build with Ktor Responds to

Chris Athanas 2 Jul 25, 2022
Checks for app updates and automatically updates the current app if the new one in local storage have a different version

Silent Android App Update Sample This sample shows how to update Android app silently without user confirmation with a device owner app. It works on A

Hamdi Guerbej 1 May 14, 2022
Candroid does things different. The Candroid app store is a library of APK client wrappers (F-Droid, APKPure, etc.) For the main Candroid app store, try visiting the Candroid Market.

Candroid App Store Candroid does things different. The Candroid app store is a library of APK client wrappers (F-Droid, APKPure, etc.) For the main Ca

Sean P. Myrick V19.1.7.2 4 Dec 22, 2022
Android app that shows what happened today in the history.

Today History Android app Master: Develop: Code Coverage: App that shows what happened today in history. Details Written in Kotlin. Android Studio 2.1

MakinGIANTS 29 Oct 3, 2022
🎶 Chromatic tuner app for Android

Chroma Chroma is a chromatic tuner, the perfect app to help you tune your musical instruments with precision and elegance. Features: Basic and complet

Adriel Café 76 Nov 30, 2022
This is a work-in-progress (🔧️) ultraviolet index viewer app for demonstrating Instant Apps + Kotlin + Dagger + MVP

UV Index A simple ultraviolet index viewer app for demonstrating: Instant Apps + Kotlin + Dagger + MVP Built With Weatherbit as weather API Android In

Mustafa Berkay Mutlu 65 Oct 31, 2022