├── settings.gradle ├── art ├── ic_launcher.sketch └── kotlin-android-developers.png ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── app ├── src │ ├── main │ │ ├── res │ │ │ ├── mipmap-hdpi │ │ │ │ └── ic_launcher.png │ │ │ ├── mipmap-mdpi │ │ │ │ └── ic_launcher.png │ │ │ ├── mipmap-xhdpi │ │ │ │ └── ic_launcher.png │ │ │ ├── mipmap-xxhdpi │ │ │ │ └── ic_launcher.png │ │ │ ├── mipmap-xxxhdpi │ │ │ │ └── ic_launcher.png │ │ │ ├── values │ │ │ │ ├── strings.xml │ │ │ │ ├── dimens.xml │ │ │ │ └── styles.xml │ │ │ ├── xml │ │ │ │ └── network_security_config.xml │ │ │ ├── values-w820dp │ │ │ │ └── dimens.xml │ │ │ ├── menu │ │ │ │ └── menu_main.xml │ │ │ └── layout │ │ │ │ ├── toolbar.xml │ │ │ │ ├── activity_main.xml │ │ │ │ ├── activity_settings.xml │ │ │ │ ├── item_forecast.xml │ │ │ │ └── activity_detail.xml │ │ ├── java │ │ │ └── com │ │ │ │ └── antonioleiva │ │ │ │ └── weatherapp │ │ │ │ ├── domain │ │ │ │ ├── commands │ │ │ │ │ ├── Command.kt │ │ │ │ │ ├── RequestDayForecastCommand.kt │ │ │ │ │ └── RequestForecastCommand.kt │ │ │ │ ├── datasource │ │ │ │ │ ├── ForecastDataSource.kt │ │ │ │ │ └── ForecastProvider.kt │ │ │ │ └── model │ │ │ │ │ └── DomainClasses.kt │ │ │ │ ├── extensions │ │ │ │ ├── ContextExtensions.kt │ │ │ │ ├── ExtensionUtils.kt │ │ │ │ ├── CollectionsExtensions.kt │ │ │ │ ├── ViewExtensions.kt │ │ │ │ ├── DatabaseExtensions.kt │ │ │ │ └── DelegatesExtensions.kt │ │ │ │ ├── ui │ │ │ │ ├── App.kt │ │ │ │ ├── activities │ │ │ │ │ ├── CoroutineScopeActivity.kt │ │ │ │ │ ├── SettingsActivity.kt │ │ │ │ │ ├── MainActivity.kt │ │ │ │ │ ├── ToolbarManager.kt │ │ │ │ │ └── DetailActivity.kt │ │ │ │ └── adapters │ │ │ │ │ └── ForecastListAdapter.kt │ │ │ │ └── data │ │ │ │ ├── db │ │ │ │ ├── Tables.kt │ │ │ │ ├── DbDataMapper.kt │ │ │ │ ├── DbClasses.kt │ │ │ │ ├── ForecastDbHelper.kt │ │ │ │ └── ForecastDb.kt │ │ │ │ └── server │ │ │ │ ├── ServerClasses.kt │ │ │ │ ├── ForecastByZipCodeRequest.kt │ │ │ │ ├── ForecastServer.kt │ │ │ │ └── ServerDataMapper.kt │ │ └── AndroidManifest.xml │ ├── test │ │ └── java │ │ │ └── com │ │ │ └── antonioleiva │ │ │ └── weatherapp │ │ │ ├── SimpleTest.kt │ │ │ ├── ExtensionsTest.kt │ │ │ └── domain │ │ │ ├── commands │ │ │ └── RequestDayForecastCommandTest.kt │ │ │ └── datasource │ │ │ └── ForecastProviderTest.kt │ └── androidTest │ │ └── java │ │ └── com │ │ └── antonioleiva │ │ └── weatherapp │ │ └── SimpleInstrumentationTest.kt ├── proguard-rules.pro └── build.gradle ├── .gitignore ├── README.md └── LICENSE /settings.gradle: -------------------------------------------------------------------------------- 1 | include ':app' 2 | -------------------------------------------------------------------------------- /art/ic_launcher.sketch: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/antoniolg/Kotlin-for-Android-Developers/HEAD/art/ic_launcher.sketch -------------------------------------------------------------------------------- /art/kotlin-android-developers.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/antoniolg/Kotlin-for-Android-Developers/HEAD/art/kotlin-android-developers.png -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/antoniolg/Kotlin-for-Android-Developers/HEAD/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /app/src/main/res/mipmap-hdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/antoniolg/Kotlin-for-Android-Developers/HEAD/app/src/main/res/mipmap-hdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-mdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/antoniolg/Kotlin-for-Android-Developers/HEAD/app/src/main/res/mipmap-mdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/antoniolg/Kotlin-for-Android-Developers/HEAD/app/src/main/res/mipmap-xhdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/antoniolg/Kotlin-for-Android-Developers/HEAD/app/src/main/res/mipmap-xxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/antoniolg/Kotlin-for-Android-Developers/HEAD/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/java/com/antonioleiva/weatherapp/domain/commands/Command.kt: -------------------------------------------------------------------------------- 1 | package com.antonioleiva.weatherapp.domain.commands 2 | 3 | interface Command { 4 | suspend fun execute(): T 5 | } -------------------------------------------------------------------------------- /app/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | WeatherApp 3 | Settings 4 | City ZipCode 5 | 6 | -------------------------------------------------------------------------------- /app/src/main/java/com/antonioleiva/weatherapp/extensions/ContextExtensions.kt: -------------------------------------------------------------------------------- 1 | package com.antonioleiva.weatherapp.extensions 2 | 3 | import android.content.Context 4 | import android.support.v4.content.ContextCompat 5 | 6 | fun Context.color(res: Int): Int = ContextCompat.getColor(this, res) -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Mon Jan 28 13:13:34 CET 2019 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | distributionUrl=https\://services.gradle.org/distributions/gradle-4.10.1-all.zip 7 | -------------------------------------------------------------------------------- /app/src/main/res/xml/network_security_config.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | api.openweathermap.org 5 | 6 | -------------------------------------------------------------------------------- /app/src/test/java/com/antonioleiva/weatherapp/SimpleTest.kt: -------------------------------------------------------------------------------- 1 | package com.antonioleiva.weatherapp 2 | 3 | import org.junit.Assert.assertTrue 4 | import org.junit.Test 5 | 6 | class SimpleTest { 7 | 8 | @Test 9 | fun `unit testing works`() { 10 | assertTrue(true) 11 | } 12 | 13 | } -------------------------------------------------------------------------------- /app/src/main/res/values/dimens.xml: -------------------------------------------------------------------------------- 1 | 2 | 16dp 3 | 4 | 5 | 16dp 6 | 16dp 7 | 8 | 9 | -------------------------------------------------------------------------------- /app/src/main/res/values/styles.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 8 | 9 | -------------------------------------------------------------------------------- /app/src/main/java/com/antonioleiva/weatherapp/extensions/ExtensionUtils.kt: -------------------------------------------------------------------------------- 1 | package com.antonioleiva.weatherapp.extensions 2 | 3 | import java.text.DateFormat 4 | import java.util.* 5 | 6 | fun Long.toDateString(dateFormat: Int = DateFormat.MEDIUM): String { 7 | val df = DateFormat.getDateInstance(dateFormat, Locale.getDefault()) 8 | return df.format(this) 9 | } 10 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Generated files 2 | bin/ 3 | gen/ 4 | 5 | # Gradle files 6 | .gradle/ 7 | gradlew.bat 8 | gradlew 9 | build/ 10 | gradle.properties 11 | 12 | # Local configuration file (sdk path, etc) 13 | local.properties 14 | 15 | # Intellij project files 16 | *.iws 17 | .idea/tasks.xml 18 | .idea 19 | 20 | *.iml 21 | 22 | # OS 23 | .DS_Store 24 | 25 | # Api key 26 | app/src/main/res/values/api_key.xml -------------------------------------------------------------------------------- /app/src/main/res/values-w820dp/dimens.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 64dp 6 | 7 | -------------------------------------------------------------------------------- /app/src/main/java/com/antonioleiva/weatherapp/domain/datasource/ForecastDataSource.kt: -------------------------------------------------------------------------------- 1 | package com.antonioleiva.weatherapp.domain.datasource 2 | 3 | import com.antonioleiva.weatherapp.domain.model.Forecast 4 | import com.antonioleiva.weatherapp.domain.model.ForecastList 5 | 6 | interface ForecastDataSource { 7 | 8 | fun requestForecastByZipCode(zipCode: Long, date: Long): ForecastList? 9 | 10 | fun requestDayForecast(id: Long): Forecast? 11 | 12 | } -------------------------------------------------------------------------------- /app/src/main/java/com/antonioleiva/weatherapp/ui/App.kt: -------------------------------------------------------------------------------- 1 | package com.antonioleiva.weatherapp.ui 2 | 3 | import android.app.Application 4 | import com.antonioleiva.weatherapp.extensions.DelegatesExt 5 | 6 | class App : Application() { 7 | 8 | companion object { 9 | var instance: App by DelegatesExt.notNullSingleValue() 10 | } 11 | 12 | override fun onCreate() { 13 | super.onCreate() 14 | instance = this 15 | } 16 | } -------------------------------------------------------------------------------- /app/src/main/res/menu/menu_main.xml: -------------------------------------------------------------------------------- 1 | 2 | 6 | 11 | -------------------------------------------------------------------------------- /app/src/main/res/layout/toolbar.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | -------------------------------------------------------------------------------- /app/src/main/java/com/antonioleiva/weatherapp/domain/model/DomainClasses.kt: -------------------------------------------------------------------------------- 1 | package com.antonioleiva.weatherapp.domain.model 2 | 3 | data class ForecastList(val id: Long, val city: String, val country: String, 4 | val dailyForecast: List) { 5 | 6 | val size: Int 7 | get() = dailyForecast.size 8 | 9 | operator fun get(position: Int) = dailyForecast[position] 10 | } 11 | 12 | data class Forecast(val id: Long, val date: Long, val description: String, val high: Int, val low: Int, 13 | val iconUrl: String) -------------------------------------------------------------------------------- /app/src/main/res/layout/activity_main.xml: -------------------------------------------------------------------------------- 1 | 5 | 6 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /app/src/main/java/com/antonioleiva/weatherapp/extensions/CollectionsExtensions.kt: -------------------------------------------------------------------------------- 1 | package com.antonioleiva.weatherapp.extensions 2 | 3 | import java.util.* 4 | 5 | fun Map.toVarargArray(): Array> = 6 | map { Pair(it.key, it.value!!) }.toTypedArray() 7 | 8 | inline fun Iterable.firstResult(predicate: (T) -> R?): R { 9 | for (element in this) { 10 | val result = predicate(element) 11 | if (result != null) return result 12 | } 13 | throw NoSuchElementException("No element matching predicate was found.") 14 | } -------------------------------------------------------------------------------- /app/src/main/java/com/antonioleiva/weatherapp/extensions/ViewExtensions.kt: -------------------------------------------------------------------------------- 1 | package com.antonioleiva.weatherapp.extensions 2 | 3 | import android.content.Context 4 | import android.view.View 5 | import android.widget.TextView 6 | 7 | val View.ctx: Context 8 | get() = context 9 | 10 | var TextView.textColor: Int 11 | get() = currentTextColor 12 | set(v) = setTextColor(v) 13 | 14 | fun View.slideExit() { 15 | if (translationY == 0f) animate().translationY(-height.toFloat()) 16 | } 17 | 18 | fun View.slideEnter() { 19 | if (translationY < 0f) animate().translationY(0f) 20 | } -------------------------------------------------------------------------------- /app/src/main/java/com/antonioleiva/weatherapp/data/db/Tables.kt: -------------------------------------------------------------------------------- 1 | package com.antonioleiva.weatherapp.data.db 2 | 3 | object CityForecastTable { 4 | const val NAME = "CityForecast" 5 | const val ID = "_id" 6 | const val CITY = "city" 7 | const val COUNTRY = "country" 8 | } 9 | 10 | object DayForecastTable { 11 | const val NAME = "DayForecast" 12 | const val ID = "_id" 13 | const val DATE = "date" 14 | const val DESCRIPTION = "description" 15 | const val HIGH = "high" 16 | const val LOW = "low" 17 | const val ICON_URL = "iconUrl" 18 | const val CITY_ID = "cityId" 19 | } -------------------------------------------------------------------------------- /app/src/test/java/com/antonioleiva/weatherapp/ExtensionsTest.kt: -------------------------------------------------------------------------------- 1 | package com.antonioleiva.weatherapp 2 | 3 | import com.antonioleiva.weatherapp.extensions.toDateString 4 | import org.junit.Assert.assertEquals 5 | import org.junit.Test 6 | import java.text.DateFormat 7 | 8 | class ExtensionsTest { 9 | 10 | @Test 11 | fun `"longToDateString" returns valid value`() { 12 | assertEquals("Oct 19, 2015", 1445275635000L.toDateString()) 13 | } 14 | 15 | @Test 16 | fun `"longToDateString" with full format returns valid value`() { 17 | assertEquals("Monday, October 19, 2015", 1445275635000L.toDateString(DateFormat.FULL)) 18 | } 19 | 20 | } -------------------------------------------------------------------------------- /app/src/main/java/com/antonioleiva/weatherapp/domain/commands/RequestDayForecastCommand.kt: -------------------------------------------------------------------------------- 1 | package com.antonioleiva.weatherapp.domain.commands 2 | 3 | import com.antonioleiva.weatherapp.domain.datasource.ForecastProvider 4 | import com.antonioleiva.weatherapp.domain.model.Forecast 5 | import kotlinx.coroutines.Dispatchers 6 | import kotlinx.coroutines.withContext 7 | 8 | class RequestDayForecastCommand( 9 | val id: Long, 10 | private val forecastProvider: ForecastProvider = ForecastProvider()) : 11 | Command { 12 | 13 | override suspend fun execute() = withContext(Dispatchers.IO) { 14 | forecastProvider.requestForecast(id) 15 | } 16 | } -------------------------------------------------------------------------------- /app/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # By default, the flags in this file are appended to flags specified 3 | # in /Users/antonio/Documents/Development/Android/sdk/tools/proguard/proguard-android.txt 4 | # You can edit the include path and order by changing the proguardFiles 5 | # directive in build.gradle. 6 | # 7 | # For more details, see 8 | # http://developer.android.com/guide/developing/tools/proguard.html 9 | 10 | # Add any project specific keep options here: 11 | 12 | # If your project uses WebView with JS, uncomment the following 13 | # and specify the fully qualified class name to the JavaScript interface 14 | # class: 15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 16 | # public *; 17 | #} 18 | -------------------------------------------------------------------------------- /app/src/test/java/com/antonioleiva/weatherapp/domain/commands/RequestDayForecastCommandTest.kt: -------------------------------------------------------------------------------- 1 | package com.antonioleiva.weatherapp.domain.commands 2 | 3 | import com.antonioleiva.weatherapp.domain.datasource.ForecastProvider 4 | import kotlinx.coroutines.runBlocking 5 | import org.junit.Test 6 | import org.mockito.Mockito.mock 7 | import org.mockito.Mockito.verify 8 | 9 | class RequestDayForecastCommandTest { 10 | 11 | @Test 12 | fun `provider is called when command is executed`() { 13 | val forecastProvider = mock(ForecastProvider::class.java) 14 | val command = RequestDayForecastCommand(2, forecastProvider) 15 | 16 | runBlocking { command.execute() } 17 | 18 | verify(forecastProvider).requestForecast(2) 19 | } 20 | } -------------------------------------------------------------------------------- /app/src/main/java/com/antonioleiva/weatherapp/domain/commands/RequestForecastCommand.kt: -------------------------------------------------------------------------------- 1 | package com.antonioleiva.weatherapp.domain.commands 2 | 3 | import com.antonioleiva.weatherapp.domain.datasource.ForecastProvider 4 | import com.antonioleiva.weatherapp.domain.model.ForecastList 5 | import kotlinx.coroutines.Dispatchers 6 | import kotlinx.coroutines.withContext 7 | 8 | class RequestForecastCommand( 9 | private val zipCode: Long, 10 | private val forecastProvider: ForecastProvider = ForecastProvider()) : 11 | Command { 12 | 13 | companion object { 14 | const val DAYS = 7 15 | } 16 | 17 | override suspend fun execute() = withContext(Dispatchers.IO) { 18 | forecastProvider.requestByZipCode(zipCode, DAYS) 19 | } 20 | } -------------------------------------------------------------------------------- /app/src/main/java/com/antonioleiva/weatherapp/data/server/ServerClasses.kt: -------------------------------------------------------------------------------- 1 | package com.antonioleiva.weatherapp.data.server 2 | 3 | data class ForecastResult(val city: City, val list: List) 4 | data class City(val id: Long, val name: String, val coord: Coordinates, val country: String, val population: Int) 5 | data class Coordinates(val lon: Float, val lat: Float) 6 | data class Forecast(val dt: Long, val temp: Temperature, val pressure: Float, val humidity: Int, 7 | val weather: List, val speed: Float, val deg: Int, val clouds: Int, val rain: Float) 8 | 9 | data class Temperature(val day: Float, val min: Float, val max: Float, val night: Float, val eve: Float, val morn: Float) 10 | data class Weather(val id: Long, val main: String, val description: String, val icon: String) -------------------------------------------------------------------------------- /app/src/main/java/com/antonioleiva/weatherapp/ui/activities/CoroutineScopeActivity.kt: -------------------------------------------------------------------------------- 1 | package com.antonioleiva.weatherapp.ui.activities 2 | 3 | import android.os.Bundle 4 | import android.support.v7.app.AppCompatActivity 5 | import kotlinx.coroutines.CoroutineScope 6 | import kotlinx.coroutines.Dispatchers 7 | import kotlinx.coroutines.Job 8 | import kotlin.coroutines.CoroutineContext 9 | 10 | abstract class CoroutineScopeActivity : AppCompatActivity(), CoroutineScope { 11 | 12 | override val coroutineContext: CoroutineContext 13 | get() = Dispatchers.Main + job 14 | 15 | lateinit var job: Job 16 | 17 | override fun onCreate(savedInstanceState: Bundle?) { 18 | super.onCreate(savedInstanceState) 19 | job = Job() 20 | } 21 | 22 | override fun onDestroy() { 23 | job.cancel() 24 | super.onDestroy() 25 | } 26 | } -------------------------------------------------------------------------------- /app/src/main/java/com/antonioleiva/weatherapp/data/server/ForecastByZipCodeRequest.kt: -------------------------------------------------------------------------------- 1 | package com.antonioleiva.weatherapp.data.server 2 | 3 | import android.util.Log 4 | import com.google.gson.Gson 5 | import java.net.URL 6 | 7 | class ForecastByZipCodeRequest(private val zipCode: Long, val gson: Gson = Gson()) { 8 | 9 | companion object { 10 | private const val APP_ID = "15646a06818f61f7b8d7823ca833e1ce" 11 | private const val URL = "http://api.openweathermap.org/data/2.5/forecast/daily?mode=json&units=metric&cnt=7" 12 | private const val COMPLETE_URL = "$URL&APPID=$APP_ID&zip=" 13 | } 14 | 15 | fun execute(): ForecastResult { 16 | val url = COMPLETE_URL + zipCode 17 | Log.d("Url", url) 18 | val forecastJsonStr = URL(url).readText() 19 | return gson.fromJson(forecastJsonStr, ForecastResult::class.java) 20 | } 21 | } -------------------------------------------------------------------------------- /app/src/main/java/com/antonioleiva/weatherapp/extensions/DatabaseExtensions.kt: -------------------------------------------------------------------------------- 1 | package com.antonioleiva.weatherapp.extensions 2 | 3 | import android.database.sqlite.SQLiteDatabase 4 | import org.jetbrains.anko.db.MapRowParser 5 | import org.jetbrains.anko.db.SelectQueryBuilder 6 | 7 | fun SelectQueryBuilder.parseList(parser: (Map) -> T): List = 8 | parseList(object : MapRowParser { 9 | override fun parseRow(columns: Map): T = parser(columns) 10 | }) 11 | 12 | fun SelectQueryBuilder.parseOpt(parser: (Map) -> T): T? = 13 | parseOpt(object : MapRowParser { 14 | override fun parseRow(columns: Map): T = parser(columns) 15 | }) 16 | 17 | fun SQLiteDatabase.clear(tableName: String) { 18 | execSQL("delete from $tableName") 19 | } 20 | 21 | fun SelectQueryBuilder.byId(id: Long) = whereSimple("_id = ?", id.toString()) 22 | -------------------------------------------------------------------------------- /app/src/main/java/com/antonioleiva/weatherapp/data/server/ForecastServer.kt: -------------------------------------------------------------------------------- 1 | package com.antonioleiva.weatherapp.data.server 2 | 3 | import com.antonioleiva.weatherapp.data.db.ForecastDb 4 | import com.antonioleiva.weatherapp.domain.datasource.ForecastDataSource 5 | import com.antonioleiva.weatherapp.domain.model.ForecastList 6 | 7 | class ForecastServer(private val dataMapper: ServerDataMapper = ServerDataMapper(), 8 | private val forecastDb: ForecastDb = ForecastDb()) : ForecastDataSource { 9 | 10 | override fun requestForecastByZipCode(zipCode: Long, date: Long): ForecastList? { 11 | val result = ForecastByZipCodeRequest(zipCode).execute() 12 | val converted = dataMapper.convertToDomain(zipCode, result) 13 | forecastDb.saveForecast(converted) 14 | return forecastDb.requestForecastByZipCode(zipCode, date) 15 | } 16 | 17 | override fun requestDayForecast(id: Long) = throw UnsupportedOperationException() 18 | } -------------------------------------------------------------------------------- /app/src/main/java/com/antonioleiva/weatherapp/data/db/DbDataMapper.kt: -------------------------------------------------------------------------------- 1 | package com.antonioleiva.weatherapp.data.db 2 | 3 | import com.antonioleiva.weatherapp.domain.model.Forecast 4 | import com.antonioleiva.weatherapp.domain.model.ForecastList 5 | 6 | class DbDataMapper { 7 | 8 | fun convertFromDomain(forecast: ForecastList) = with(forecast) { 9 | val daily = dailyForecast.map { convertDayFromDomain(id, it) } 10 | CityForecast(id, city, country, daily) 11 | } 12 | 13 | private fun convertDayFromDomain(cityId: Long, forecast: Forecast) = with(forecast) { 14 | DayForecast(date, description, high, low, iconUrl, cityId) 15 | } 16 | 17 | fun convertToDomain(forecast: CityForecast) = with(forecast) { 18 | val daily = dailyForecast.map { convertDayToDomain(it) } 19 | ForecastList(_id, city, country, daily) 20 | } 21 | 22 | fun convertDayToDomain(dayForecast: DayForecast) = with(dayForecast) { 23 | Forecast(_id, date, description, high, low, iconUrl) 24 | } 25 | } -------------------------------------------------------------------------------- /app/src/main/res/layout/activity_settings.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | 8 | 9 | 10 | 16 | 17 | 21 | 22 | 28 | 29 | 30 | 31 | -------------------------------------------------------------------------------- /app/src/main/java/com/antonioleiva/weatherapp/data/db/DbClasses.kt: -------------------------------------------------------------------------------- 1 | package com.antonioleiva.weatherapp.data.db 2 | 3 | import java.util.* 4 | 5 | class CityForecast(val map: MutableMap, val dailyForecast: List) { 6 | var _id: Long by map 7 | var city: String by map 8 | var country: String by map 9 | 10 | constructor(id: Long, city: String, country: String, dailyForecast: List) 11 | : this(HashMap(), dailyForecast) { 12 | this._id = id 13 | this.city = city 14 | this.country = country 15 | } 16 | } 17 | 18 | class DayForecast(var map: MutableMap) { 19 | var _id: Long by map 20 | var date: Long by map 21 | var description: String by map 22 | var high: Int by map 23 | var low: Int by map 24 | var iconUrl: String by map 25 | var cityId: Long by map 26 | 27 | constructor(date: Long, description: String, high: Int, low: Int, iconUrl: String, cityId: Long) 28 | : this(HashMap()) { 29 | this.date = date 30 | this.description = description 31 | this.high = high 32 | this.low = low 33 | this.iconUrl = iconUrl 34 | this.cityId = cityId 35 | } 36 | } -------------------------------------------------------------------------------- /app/src/test/java/com/antonioleiva/weatherapp/domain/datasource/ForecastProviderTest.kt: -------------------------------------------------------------------------------- 1 | package com.antonioleiva.weatherapp.domain.datasource 2 | 3 | import com.antonioleiva.weatherapp.domain.model.Forecast 4 | import com.antonioleiva.weatherapp.domain.model.ForecastList 5 | import org.junit.Assert.assertNotNull 6 | import org.junit.Test 7 | import org.mockito.Mockito.* 8 | 9 | class ForecastProviderTest { 10 | 11 | @Test 12 | fun `data source returns a value`() { 13 | val ds = mock(ForecastDataSource::class.java) 14 | `when`(ds.requestDayForecast(0)).then { Forecast(0, 0, "desc", 20, 0, "url") } 15 | 16 | val provider = ForecastProvider(listOf(ds)) 17 | assertNotNull(provider.requestForecast(0)) 18 | } 19 | 20 | @Test 21 | fun `empty database returns server value`() { 22 | val db = mock(ForecastDataSource::class.java) 23 | val server = mock(ForecastDataSource::class.java) 24 | `when`(server.requestForecastByZipCode(any(Long::class.java), any(Long::class.java))) 25 | .then { ForecastList(0, "city", "country", listOf()) } 26 | 27 | val provider = ForecastProvider(listOf(db, server)) 28 | assertNotNull(provider.requestByZipCode(0, 0)) 29 | } 30 | 31 | } -------------------------------------------------------------------------------- /app/src/main/java/com/antonioleiva/weatherapp/data/server/ServerDataMapper.kt: -------------------------------------------------------------------------------- 1 | package com.antonioleiva.weatherapp.data.server 2 | 3 | import com.antonioleiva.weatherapp.domain.model.ForecastList 4 | import java.util.* 5 | import java.util.concurrent.TimeUnit 6 | import com.antonioleiva.weatherapp.domain.model.Forecast as ModelForecast 7 | 8 | class ServerDataMapper { 9 | 10 | fun convertToDomain(zipCode: Long, forecast: ForecastResult) = with(forecast) { 11 | ForecastList(zipCode, city.name, city.country, convertForecastListToDomain(list)) 12 | } 13 | 14 | private fun convertForecastListToDomain(list: List): List { 15 | return list.mapIndexed { i, forecast -> 16 | val dt = Calendar.getInstance().timeInMillis + TimeUnit.DAYS.toMillis(i.toLong()) 17 | convertForecastItemToDomain(forecast.copy(dt = dt)) 18 | } 19 | } 20 | 21 | private fun convertForecastItemToDomain(forecast: Forecast) = with(forecast) { 22 | ModelForecast(-1, dt, weather[0].description, temp.max.toInt(), temp.min.toInt(), 23 | generateIconUrl(weather[0].icon)) 24 | } 25 | 26 | private fun generateIconUrl(iconCode: String) = "http://openweathermap.org/img/w/$iconCode.png" 27 | } -------------------------------------------------------------------------------- /app/src/main/java/com/antonioleiva/weatherapp/domain/datasource/ForecastProvider.kt: -------------------------------------------------------------------------------- 1 | package com.antonioleiva.weatherapp.domain.datasource 2 | 3 | import com.antonioleiva.weatherapp.data.db.ForecastDb 4 | import com.antonioleiva.weatherapp.data.server.ForecastServer 5 | import com.antonioleiva.weatherapp.domain.model.Forecast 6 | import com.antonioleiva.weatherapp.domain.model.ForecastList 7 | import com.antonioleiva.weatherapp.extensions.firstResult 8 | 9 | class ForecastProvider(private val sources: List = ForecastProvider.SOURCES) { 10 | 11 | companion object { 12 | const val DAY_IN_MILLIS = 1000 * 60 * 60 * 24 13 | val SOURCES by lazy { listOf(ForecastDb(), ForecastServer()) } 14 | } 15 | 16 | fun requestByZipCode(zipCode: Long, days: Int): ForecastList = requestToSources { 17 | val res = it.requestForecastByZipCode(zipCode, todayTimeSpan()) 18 | if (res != null && res.size >= days) res else null 19 | } 20 | 21 | fun requestForecast(id: Long): Forecast = requestToSources { it.requestDayForecast(id) } 22 | 23 | private fun todayTimeSpan() = System.currentTimeMillis() / DAY_IN_MILLIS * DAY_IN_MILLIS 24 | 25 | private fun requestToSources(f: (ForecastDataSource) -> T?): T = sources.firstResult { f(it) } 26 | 27 | } -------------------------------------------------------------------------------- /app/src/main/java/com/antonioleiva/weatherapp/ui/activities/SettingsActivity.kt: -------------------------------------------------------------------------------- 1 | package com.antonioleiva.weatherapp.ui.activities 2 | 3 | import android.os.Bundle 4 | import android.support.v7.app.AppCompatActivity 5 | import android.view.MenuItem 6 | import com.antonioleiva.weatherapp.R 7 | import com.antonioleiva.weatherapp.extensions.DelegatesExt 8 | import kotlinx.android.synthetic.main.activity_settings.* 9 | import kotlinx.android.synthetic.main.toolbar.* 10 | 11 | class SettingsActivity : AppCompatActivity() { 12 | 13 | companion object { 14 | const val ZIP_CODE = "zipCode" 15 | const val DEFAULT_ZIP = 94043L 16 | } 17 | 18 | private var zipCode: Long by DelegatesExt.preference(this, ZIP_CODE, DEFAULT_ZIP) 19 | 20 | override fun onCreate(savedInstanceState: Bundle?) { 21 | super.onCreate(savedInstanceState) 22 | setContentView(R.layout.activity_settings) 23 | setSupportActionBar(toolbar) 24 | supportActionBar?.setDisplayHomeAsUpEnabled(true) 25 | cityCode.setText(zipCode.toString()) 26 | } 27 | 28 | override fun onBackPressed() { 29 | super.onBackPressed() 30 | zipCode = cityCode.text.toString().toLong() 31 | } 32 | 33 | override fun onOptionsItemSelected(item: MenuItem) = when (item.itemId) { 34 | android.R.id.home -> { 35 | onBackPressed() 36 | true 37 | } 38 | else -> false 39 | } 40 | } -------------------------------------------------------------------------------- /app/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | 7 | 8 | 15 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 27 | 30 | 31 | 34 | 35 | 36 | 37 | 38 | -------------------------------------------------------------------------------- /app/src/main/java/com/antonioleiva/weatherapp/data/db/ForecastDbHelper.kt: -------------------------------------------------------------------------------- 1 | package com.antonioleiva.weatherapp.data.db 2 | 3 | import android.content.Context 4 | import android.database.sqlite.SQLiteDatabase 5 | import com.antonioleiva.weatherapp.ui.App 6 | import org.jetbrains.anko.db.* 7 | 8 | class ForecastDbHelper(ctx: Context = App.instance) : ManagedSQLiteOpenHelper(ctx, 9 | ForecastDbHelper.DB_NAME, null, ForecastDbHelper.DB_VERSION) { 10 | 11 | companion object { 12 | const val DB_NAME = "forecast.db" 13 | const val DB_VERSION = 1 14 | val instance by lazy { ForecastDbHelper() } 15 | } 16 | 17 | override fun onCreate(db: SQLiteDatabase) { 18 | db.createTable(CityForecastTable.NAME, true, 19 | CityForecastTable.ID to INTEGER + PRIMARY_KEY, 20 | CityForecastTable.CITY to TEXT, 21 | CityForecastTable.COUNTRY to TEXT) 22 | 23 | db.createTable(DayForecastTable.NAME, true, 24 | DayForecastTable.ID to INTEGER + PRIMARY_KEY + AUTOINCREMENT, 25 | DayForecastTable.DATE to INTEGER, 26 | DayForecastTable.DESCRIPTION to TEXT, 27 | DayForecastTable.HIGH to INTEGER, 28 | DayForecastTable.LOW to INTEGER, 29 | DayForecastTable.ICON_URL to TEXT, 30 | DayForecastTable.CITY_ID to INTEGER) 31 | } 32 | 33 | override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) { 34 | db.dropTable(CityForecastTable.NAME, true) 35 | db.dropTable(DayForecastTable.NAME, true) 36 | onCreate(db) 37 | } 38 | } 39 | 40 | -------------------------------------------------------------------------------- /app/src/main/java/com/antonioleiva/weatherapp/ui/activities/MainActivity.kt: -------------------------------------------------------------------------------- 1 | package com.antonioleiva.weatherapp.ui.activities 2 | 3 | import android.os.Bundle 4 | import android.support.v7.widget.LinearLayoutManager 5 | import android.support.v7.widget.Toolbar 6 | import com.antonioleiva.weatherapp.R 7 | import com.antonioleiva.weatherapp.domain.commands.RequestForecastCommand 8 | import com.antonioleiva.weatherapp.extensions.DelegatesExt 9 | import com.antonioleiva.weatherapp.ui.adapters.ForecastListAdapter 10 | import kotlinx.android.synthetic.main.activity_main.* 11 | import kotlinx.coroutines.launch 12 | import org.jetbrains.anko.find 13 | import org.jetbrains.anko.startActivity 14 | 15 | class MainActivity : CoroutineScopeActivity(), ToolbarManager { 16 | 17 | private val zipCode: Long by DelegatesExt.preference(this, SettingsActivity.ZIP_CODE, 18 | SettingsActivity.DEFAULT_ZIP) 19 | override val toolbar by lazy { find(R.id.toolbar) } 20 | 21 | override fun onCreate(savedInstanceState: Bundle?) { 22 | super.onCreate(savedInstanceState) 23 | setContentView(R.layout.activity_main) 24 | initToolbar() 25 | 26 | forecastList.layoutManager = LinearLayoutManager(this) 27 | attachToScroll(forecastList) 28 | } 29 | 30 | override fun onResume() { 31 | super.onResume() 32 | loadForecast() 33 | } 34 | 35 | private fun loadForecast() = launch { 36 | val result = RequestForecastCommand(zipCode).execute() 37 | val adapter = ForecastListAdapter(result) { 38 | startActivity(DetailActivity.ID to it.id, 39 | DetailActivity.CITY_NAME to result.city) 40 | } 41 | forecastList.adapter = adapter 42 | toolbarTitle = "${result.city} (${result.country})" 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /app/src/main/java/com/antonioleiva/weatherapp/ui/activities/ToolbarManager.kt: -------------------------------------------------------------------------------- 1 | package com.antonioleiva.weatherapp.ui.activities 2 | 3 | import android.support.v7.graphics.drawable.DrawerArrowDrawable 4 | import android.support.v7.widget.RecyclerView 5 | import android.support.v7.widget.Toolbar 6 | import com.antonioleiva.weatherapp.R 7 | import com.antonioleiva.weatherapp.extensions.ctx 8 | import com.antonioleiva.weatherapp.extensions.slideEnter 9 | import com.antonioleiva.weatherapp.extensions.slideExit 10 | import com.antonioleiva.weatherapp.ui.App 11 | import org.jetbrains.anko.startActivity 12 | import org.jetbrains.anko.toast 13 | 14 | interface ToolbarManager { 15 | 16 | val toolbar: Toolbar 17 | 18 | var toolbarTitle: String 19 | get() = toolbar.title.toString() 20 | set(value) { 21 | toolbar.title = value 22 | } 23 | 24 | fun initToolbar() { 25 | toolbar.inflateMenu(R.menu.menu_main) 26 | toolbar.setOnMenuItemClickListener { 27 | when (it.itemId) { 28 | R.id.action_settings -> toolbar.ctx.startActivity() 29 | else -> App.instance.toast("Unknown option") 30 | } 31 | true 32 | } 33 | } 34 | 35 | fun enableHomeAsUp(up: () -> Unit) { 36 | toolbar.navigationIcon = createUpDrawable() 37 | toolbar.setNavigationOnClickListener { up() } 38 | } 39 | 40 | private fun createUpDrawable() = DrawerArrowDrawable(toolbar.ctx).apply { progress = 1f } 41 | 42 | fun attachToScroll(recyclerView: RecyclerView) { 43 | recyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() { 44 | override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) { 45 | if (dy > 0) toolbar.slideExit() else toolbar.slideEnter() 46 | } 47 | }) 48 | } 49 | } -------------------------------------------------------------------------------- /app/src/main/java/com/antonioleiva/weatherapp/data/db/ForecastDb.kt: -------------------------------------------------------------------------------- 1 | package com.antonioleiva.weatherapp.data.db 2 | 3 | import com.antonioleiva.weatherapp.domain.datasource.ForecastDataSource 4 | import com.antonioleiva.weatherapp.domain.model.ForecastList 5 | import com.antonioleiva.weatherapp.extensions.* 6 | import org.jetbrains.anko.db.insert 7 | import org.jetbrains.anko.db.select 8 | import java.util.* 9 | 10 | class ForecastDb(private val forecastDbHelper: ForecastDbHelper = ForecastDbHelper.instance, 11 | private val dataMapper: DbDataMapper = DbDataMapper()) : ForecastDataSource { 12 | 13 | override fun requestForecastByZipCode(zipCode: Long, date: Long) = forecastDbHelper.use { 14 | 15 | val dailyRequest = "${DayForecastTable.CITY_ID} = ? AND ${DayForecastTable.DATE} >= ?" 16 | val dailyForecast = select(DayForecastTable.NAME) 17 | .whereSimple(dailyRequest, zipCode.toString(), date.toString()) 18 | .parseList { DayForecast(HashMap(it)) } 19 | 20 | val city = select(CityForecastTable.NAME) 21 | .whereSimple("${CityForecastTable.ID} = ?", zipCode.toString()) 22 | .parseOpt { CityForecast(HashMap(it), dailyForecast) } 23 | 24 | city?.let { dataMapper.convertToDomain(it) } 25 | } 26 | 27 | override fun requestDayForecast(id: Long) = forecastDbHelper.use { 28 | val forecast = select(DayForecastTable.NAME).byId(id). 29 | parseOpt { DayForecast(HashMap(it)) } 30 | 31 | forecast?.let { dataMapper.convertDayToDomain(it) } 32 | } 33 | 34 | fun saveForecast(forecast: ForecastList) = forecastDbHelper.use { 35 | 36 | clear(CityForecastTable.NAME) 37 | clear(DayForecastTable.NAME) 38 | 39 | with(dataMapper.convertFromDomain(forecast)) { 40 | insert(CityForecastTable.NAME, *map.toVarargArray()) 41 | dailyForecast.forEach { insert(DayForecastTable.NAME, *it.map.toVarargArray()) } 42 | } 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /app/src/main/java/com/antonioleiva/weatherapp/ui/adapters/ForecastListAdapter.kt: -------------------------------------------------------------------------------- 1 | package com.antonioleiva.weatherapp.ui.adapters 2 | 3 | import android.annotation.SuppressLint 4 | import android.support.v7.widget.RecyclerView 5 | import android.view.LayoutInflater 6 | import android.view.View 7 | import android.view.ViewGroup 8 | import com.antonioleiva.weatherapp.R 9 | import com.antonioleiva.weatherapp.domain.model.Forecast 10 | import com.antonioleiva.weatherapp.domain.model.ForecastList 11 | import com.antonioleiva.weatherapp.extensions.ctx 12 | import com.antonioleiva.weatherapp.extensions.toDateString 13 | import com.squareup.picasso.Picasso 14 | import kotlinx.android.extensions.LayoutContainer 15 | import kotlinx.android.synthetic.main.item_forecast.* 16 | 17 | class ForecastListAdapter(private val weekForecast: ForecastList, 18 | private val itemClick: (Forecast) -> Unit) : 19 | RecyclerView.Adapter() { 20 | 21 | override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { 22 | val view = LayoutInflater.from(parent.ctx).inflate(R.layout.item_forecast, parent, false) 23 | return ViewHolder(view, itemClick) 24 | } 25 | 26 | @SuppressLint("SetTextI18n") 27 | override fun onBindViewHolder(holder: ViewHolder, position: Int) { 28 | holder.bindForecast(weekForecast[position]) 29 | } 30 | 31 | override fun getItemCount() = weekForecast.size 32 | 33 | class ViewHolder(override val containerView: View, private val itemClick: (Forecast) -> Unit) 34 | : RecyclerView.ViewHolder(containerView), LayoutContainer { 35 | 36 | fun bindForecast(forecast: Forecast) { 37 | with(forecast) { 38 | Picasso.with(itemView.ctx).load(iconUrl).into(icon) 39 | dateText.text = date.toDateString() 40 | descriptionText.text = description 41 | maxTemperature.text = "${high}º" 42 | minTemperature.text = "${low}º" 43 | itemView.setOnClickListener { itemClick(this) } 44 | } 45 | } 46 | } 47 | } -------------------------------------------------------------------------------- /app/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.application' 2 | apply plugin: 'kotlin-android' 3 | apply plugin: 'kotlin-android-extensions' 4 | 5 | android { 6 | compileSdkVersion 28 7 | 8 | defaultConfig { 9 | applicationId "com.antonioleiva.weatherapp" 10 | minSdkVersion 15 11 | targetSdkVersion 28 12 | versionCode 1 13 | versionName "1.0" 14 | 15 | testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" 16 | } 17 | 18 | buildTypes { 19 | release { 20 | minifyEnabled false 21 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 22 | } 23 | } 24 | } 25 | 26 | androidExtensions { 27 | experimental = true 28 | } 29 | 30 | dependencies { 31 | implementation fileTree(dir: 'libs', include: ['*.jar']) 32 | implementation "com.android.support:appcompat-v7:$support_version" 33 | implementation "com.android.support:recyclerview-v7:$support_version" 34 | implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version" 35 | implementation "org.jetbrains.anko:anko-common:$anko_version" 36 | implementation "org.jetbrains.anko:anko-sqlite:$anko_version" 37 | implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.1.0' 38 | implementation "com.google.code.gson:gson:2.8.5" 39 | implementation "com.squareup.picasso:picasso:2.5.2" 40 | 41 | testImplementation "junit:junit:4.12" 42 | testImplementation "org.mockito:mockito-core:$mockito_version" 43 | testImplementation "org.mockito:mockito-inline:$mockito_version" 44 | 45 | androidTestImplementation "com.android.support:support-annotations:$support_version" 46 | androidTestImplementation "com.android.support.test:runner:$test_support_version" 47 | androidTestImplementation "com.android.support.test:rules:$test_support_version" 48 | androidTestImplementation "com.android.support.test.espresso:espresso-core:$espresso_version" 49 | androidTestImplementation("com.android.support.test.espresso:espresso-contrib:$espresso_version") { 50 | exclude group: 'com.android.support', module: 'appcompat-v7' 51 | exclude group: 'com.android.support', module: 'support-v4' 52 | exclude group: 'com.android.support', module: 'design' 53 | exclude group: 'com.android.support', module: 'recyclerview-v7' 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /app/src/main/java/com/antonioleiva/weatherapp/ui/activities/DetailActivity.kt: -------------------------------------------------------------------------------- 1 | package com.antonioleiva.weatherapp.ui.activities 2 | 3 | import android.annotation.SuppressLint 4 | import android.os.Bundle 5 | import android.support.v7.widget.Toolbar 6 | import android.widget.TextView 7 | import com.antonioleiva.weatherapp.R 8 | import com.antonioleiva.weatherapp.domain.commands.RequestDayForecastCommand 9 | import com.antonioleiva.weatherapp.domain.model.Forecast 10 | import com.antonioleiva.weatherapp.extensions.color 11 | import com.antonioleiva.weatherapp.extensions.textColor 12 | import com.antonioleiva.weatherapp.extensions.toDateString 13 | import com.squareup.picasso.Picasso 14 | import kotlinx.android.synthetic.main.activity_detail.* 15 | import kotlinx.coroutines.launch 16 | import org.jetbrains.anko.find 17 | import java.text.DateFormat 18 | 19 | class DetailActivity : CoroutineScopeActivity(), ToolbarManager { 20 | 21 | override val toolbar by lazy { find(R.id.toolbar) } 22 | 23 | companion object { 24 | const val ID = "DetailActivity:id" 25 | const val CITY_NAME = "DetailActivity:cityName" 26 | } 27 | 28 | override fun onCreate(savedInstanceState: Bundle?) { 29 | super.onCreate(savedInstanceState) 30 | setContentView(R.layout.activity_detail) 31 | initToolbar() 32 | 33 | toolbarTitle = intent.getStringExtra(CITY_NAME) 34 | enableHomeAsUp { onBackPressed() } 35 | 36 | launch { 37 | val id = intent.getLongExtra(ID, -1) 38 | val result = RequestDayForecastCommand(id).execute() 39 | bindForecast(result) 40 | } 41 | } 42 | 43 | private fun bindForecast(forecast: Forecast) = with(forecast) { 44 | Picasso.with(this@DetailActivity).load(iconUrl).into(icon) 45 | toolbar.subtitle = date.toDateString(DateFormat.FULL) 46 | weatherDescription.text = description 47 | bindWeather(high to maxTemperature, low to minTemperature) 48 | } 49 | 50 | @SuppressLint("SetTextI18n") 51 | private fun bindWeather(vararg views: Pair) = views.forEach { 52 | it.second.text = "${it.first}º" 53 | it.second.textColor = color(when (it.first) { 54 | in -50..0 -> android.R.color.holo_red_dark 55 | in 0..15 -> android.R.color.holo_orange_dark 56 | else -> android.R.color.holo_green_dark 57 | }) 58 | } 59 | } -------------------------------------------------------------------------------- /app/src/androidTest/java/com/antonioleiva/weatherapp/SimpleInstrumentationTest.kt: -------------------------------------------------------------------------------- 1 | package com.antonioleiva.weatherapp 2 | 3 | import android.support.test.espresso.Espresso.* 4 | import android.support.test.espresso.action.ViewActions.click 5 | import android.support.test.espresso.action.ViewActions.replaceText 6 | import android.support.test.espresso.assertion.ViewAssertions.matches 7 | import android.support.test.espresso.contrib.RecyclerViewActions 8 | import android.support.test.espresso.matcher.BoundedMatcher 9 | import android.support.test.espresso.matcher.ViewMatchers.* 10 | import android.support.test.rule.ActivityTestRule 11 | import android.support.v7.widget.RecyclerView 12 | import android.support.v7.widget.Toolbar 13 | import android.widget.TextView 14 | import com.antonioleiva.weatherapp.ui.activities.MainActivity 15 | import org.hamcrest.Description 16 | import org.hamcrest.Matcher 17 | import org.hamcrest.Matchers.`is` 18 | import org.junit.Rule 19 | import org.junit.Test 20 | 21 | class SimpleInstrumentationTest { 22 | 23 | @get:Rule 24 | val activityRule = ActivityTestRule(MainActivity::class.java) 25 | 26 | @Test fun itemClickNavigatesToDetail() { 27 | onView(withId(R.id.forecastList)).perform( 28 | RecyclerViewActions.actionOnItemAtPosition(0, click())) 29 | onView(withId(R.id.weatherDescription)) 30 | .check(matches(isAssignableFrom(TextView::class.java))) 31 | } 32 | 33 | @Test fun modifyZipCodeChangesToolbarTitle() { 34 | openActionBarOverflowOrOptionsMenu(activityRule.activity) 35 | onView(withText(R.string.settings)).perform(click()) 36 | onView(withId(R.id.cityCode)).perform(replaceText("94301")) 37 | pressBack() 38 | onView(isAssignableFrom(Toolbar::class.java)) 39 | .check(matches(withToolbarTitle(`is`("Palo Alto (US)")))) 40 | } 41 | 42 | private fun withToolbarTitle(textMatcher: Matcher): Matcher = 43 | object : BoundedMatcher(Toolbar::class.java) { 44 | 45 | override fun matchesSafely(toolbar: Toolbar): Boolean = 46 | textMatcher.matches(toolbar.title) 47 | 48 | override fun describeTo(description: Description) { 49 | description.appendText("with toolbar title: ") 50 | textMatcher.describeTo(description) 51 | } 52 | } 53 | } -------------------------------------------------------------------------------- /app/src/main/res/layout/item_forecast.xml: -------------------------------------------------------------------------------- 1 | 2 | 11 | 12 | 17 | 18 | 25 | 26 | 32 | 33 | 39 | 40 | 41 | 42 | 47 | 48 | 54 | 55 | 61 | 62 | 63 | 64 | -------------------------------------------------------------------------------- /app/src/main/res/layout/activity_detail.xml: -------------------------------------------------------------------------------- 1 | 7 | 8 | 9 | 10 | 19 | 20 | 26 | 27 | 34 | 35 | 36 | 37 | 40 | 41 | 50 | 51 | 60 | 61 | 62 | 63 | 64 | -------------------------------------------------------------------------------- /app/src/main/java/com/antonioleiva/weatherapp/extensions/DelegatesExtensions.kt: -------------------------------------------------------------------------------- 1 | package com.antonioleiva.weatherapp.extensions 2 | 3 | import android.annotation.SuppressLint 4 | import android.content.Context 5 | import android.content.SharedPreferences 6 | import kotlin.reflect.KProperty 7 | 8 | object DelegatesExt { 9 | fun notNullSingleValue() = NotNullSingleValueVar() 10 | fun preference(context: Context, name: String, 11 | default: T) = Preference(context, name, default) 12 | } 13 | 14 | class NotNullSingleValueVar { 15 | 16 | private var value: T? = null 17 | 18 | operator fun getValue(thisRef: Any?, property: KProperty<*>): T = 19 | value ?: throw IllegalStateException("${property.name} not initialized") 20 | 21 | operator fun setValue(thisRef: Any?, property: KProperty<*>, value: T) { 22 | this.value = if (this.value == null) value 23 | else throw IllegalStateException("${property.name} already initialized") 24 | } 25 | } 26 | 27 | class Preference(private val context: Context, private val name: String, 28 | private val default: T) { 29 | 30 | private val prefs: SharedPreferences by lazy { 31 | context.getSharedPreferences("default", Context.MODE_PRIVATE) 32 | } 33 | 34 | operator fun getValue(thisRef: Any?, property: KProperty<*>): T = findPreference(name, default) 35 | 36 | operator fun setValue(thisRef: Any?, property: KProperty<*>, value: T) { 37 | putPreference(name, value) 38 | } 39 | 40 | @Suppress("UNCHECKED_CAST") 41 | private fun findPreference(name: String, default: T): T = with(prefs) { 42 | val res: Any = when (default) { 43 | is Long -> getLong(name, default) 44 | is String -> getString(name, default) 45 | is Int -> getInt(name, default) 46 | is Boolean -> getBoolean(name, default) 47 | is Float -> getFloat(name, default) 48 | else -> throw IllegalArgumentException("This type can be saved into Preferences") 49 | } 50 | 51 | res as T 52 | } 53 | 54 | @SuppressLint("CommitPrefEdits") 55 | private fun putPreference(name: String, value: T) = with(prefs.edit()) { 56 | when (value) { 57 | is Long -> putLong(name, value) 58 | is String -> putString(name, value) 59 | is Int -> putInt(name, value) 60 | is Boolean -> putBoolean(name, value) 61 | is Float -> putFloat(name, value) 62 | else -> throw IllegalArgumentException("This type can't be saved into Preferences") 63 | }.apply() 64 | } 65 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Kotlin for Android Developers (the book) 2 | 3 | This is the code you can use to follow the book. 4 | 5 | [https://antonioleiva.com/kotlin-android-developers-book/](https://antonioleiva.com/kotlin-android-developers-book/) 6 | 7 | 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. 8 | 9 | And now, it's officially supported by Google! 10 | 11 | ![Kotlin for Android Developers cover](art/kotlin-android-developers.png?raw=true) 12 | 13 | ## About the book 14 | 15 | [In this book](https://antonioleiva.com/kotlin-android-developers-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. 16 | 17 | [This book](https://antonioleiva.com/kotlin-android-developers-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. 18 | 19 | [The book](https://antonioleiva.com/kotlin-android-developers-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. 20 | 21 | ## Versions 22 | 23 | As I update the book, I need to push -f this repository with the new changes, so that it matches with the new text. 24 | 25 | That means that if you are reading an old version of the book, main branches won't be aligned with your text. 26 | 27 | To make things easier, I'll keep track of those versions in separates branches, which will be linked from here: 28 | 29 | - 7th edition: February 2019 (current) 30 | - 6th edition: [April 2018](https://github.com/antoniolg/Kotlin-for-Android-Developers/tree/master-april-2018) 31 | - [5th edition: September 2017](https://github.com/antoniolg/Kotlin-for-Android-Developers/tree/master-september-2017) 32 | - [4th edition: July 2017](https://github.com/antoniolg/Kotlin-for-Android-Developers/tree/master-july-2017) 33 | - [3rd edition: June 2017](https://github.com/antoniolg/Kotlin-for-Android-Developers/tree/master-june-2017) 34 | - [2nd edition: January 2017](https://github.com/antoniolg/Kotlin-for-Android-Developers/tree/master-january-2017) 35 | - [1st edition: March 2016](https://github.com/antoniolg/Kotlin-for-Android-Developers/tree/master-march-2016) 36 | 37 | ## License 38 | 39 | Copyright 2019 Antonio Leiva 40 | 41 | Licensed under the Apache License, Version 2.0 (the "License"); 42 | you may not use this file except in compliance with the License. 43 | You may obtain a copy of the License at 44 | 45 | http://www.apache.org/licenses/LICENSE-2.0 46 | 47 | Unless required by applicable law or agreed to in writing, software 48 | distributed under the License is distributed on an "AS IS" BASIS, 49 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 50 | See the License for the specific language governing permissions and 51 | limitations under the License. -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright 2015 Antonio Leiva 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. --------------------------------------------------------------------------------