Project 2: Weather App with Retrofit and Location

Android Development 18 min min read Updated: Nov 16, 2026 Intermediate
Project 2: Weather App with Retrofit and Location
Intermediate Topic 2 of 4

What We Build

  • Search for a city
  • Show current temperature, wind and a weather icon
  • Show the next 12 hours
  • Loading, empty and error states
  • Free API with no key
The API: Open-Meteo provides free weather data for non-commercial use, with a geocoding API to find city coordinates. Read their terms before publishing an app.

1. API Models and Interface

kotlin @Serializable data class GeoResponse(val results: List<PlaceDto> = emptyList()) @Serializable data class PlaceDto(val id: Int, val name: String, val latitude: Double, val longitude: Double, val country: String? = null) @Serializable data class ForecastDto(val current: CurrentDto, val hourly: HourlyDto) { @Serializable data class CurrentDto( @SerialName("temperature_2m") val temperature: Double, @SerialName("wind_speed_10m") val windSpeed: Double, @SerialName("weather_code") val weatherCode: Int ) @Serializable data class HourlyDto(val time: List<String>, @SerialName("temperature_2m") val temperature: List<Double>) } interface GeoApi { @GET("v1/search") suspend fun search(@Query("name") name: String, @Query("count") count: Int = 5): GeoResponse } interface WeatherApi { @GET("v1/forecast") suspend fun forecast( @Query("latitude") lat: Double, @Query("longitude") lon: Double, @Query("current") current: String = "temperature_2m,wind_speed_10m,weather_code", @Query("hourly") hourly: String = "temperature_2m", @Query("forecast_days") days: Int = 2, @Query("timezone") timezone: String = "auto" ): ForecastDto } // Geo API base URL: https://geocoding-api.open-meteo.com/ Weather base URL: https://api.open-meteo.com/

2. Weather Codes to Icons

kotlin data class Condition(val text: String, val icon: ImageVector) fun conditionFor(code: Int): Condition = when (code) { 0 -> Condition("Clear sky", Icons.Default.WbSunny) 1, 2 -> Condition("Partly cloudy", Icons.Default.WbCloudy) 3 -> Condition("Overcast", Icons.Default.Cloud) 45, 48 -> Condition("Fog", Icons.Default.Foggy) in 51..67, in 80..82 -> Condition("Rain", Icons.Default.WaterDrop) in 71..77 -> Condition("Snow", Icons.Default.AcUnit) in 95..99 -> Condition("Thunderstorm", Icons.Default.Thunderstorm) else -> Condition("Unknown", Icons.Default.HelpOutline) }

3. Repository

kotlin data class Place(val id: Int, val name: String, val lat: Double, val lon: Double, val country: String) data class HourTemp(val label: String, val temp: Int) data class Weather(val place: Place, val temp: Int, val wind: Int, val condition: Condition, val hours: List<HourTemp>) class WeatherRepository(private val geo: GeoApi, private val api: WeatherApi) { suspend fun searchCity(name: String): List<Place> = geo.search(name).results.map { Place(it.id, it.name, it.latitude, it.longitude, it.country.orEmpty()) } suspend fun weather(place: Place): Weather { val f = api.forecast(place.lat, place.lon) val hours = f.hourly.time.zip(f.hourly.temperature) .map { (time, temp) -> HourTemp(time.takeLast(5), temp.roundToInt()) } .take(12) return Weather(place, f.current.temperature.roundToInt(), f.current.windSpeed.roundToInt(), conditionFor(f.current.weatherCode), hours) } }

4. ViewModel

kotlin data class WeatherUiState( val query: String = "", val suggestions: List<Place> = emptyList(), val isLoading: Boolean = false, val weather: Weather? = null, val error: String? = null ) class WeatherViewModel(private val repository: WeatherRepository) : ViewModel() { private val _state = MutableStateFlow(WeatherUiState()) val state = _state.asStateFlow() private var searchJob: Job? = null fun onQueryChange(text: String) { _state.update { it.copy(query = text) } searchJob?.cancel() if (text.length < 2) { _state.update { it.copy(suggestions = emptyList()) }; return } searchJob = viewModelScope.launch { delay(400) // debounce: wait until typing pauses runCatching { repository.searchCity(text) } .onSuccess { list -> _state.update { it.copy(suggestions = list) } } } } fun select(place: Place) = viewModelScope.launch { _state.update { it.copy(isLoading = true, error = null, suggestions = emptyList(), query = place.name) } runCatching { repository.weather(place) } .onSuccess { w -> _state.update { it.copy(weather = w, isLoading = false) } } .onFailure { _state.update { s -> s.copy(isLoading = false, error = "Could not load the weather. Check your internet.") } } } }

5. The Screen

kotlin @Composable fun WeatherScreen(viewModel: WeatherViewModel) { val state by viewModel.state.collectAsStateWithLifecycle() Column(Modifier.fillMaxSize().padding(16.dp), verticalArrangement = Arrangement.spacedBy(16.dp)) { OutlinedTextField( value = state.query, onValueChange = viewModel::onQueryChange, label = { Text("City") }, singleLine = true, modifier = Modifier.fillMaxWidth() ) state.suggestions.forEach { place -> Text("${place.name}, ${place.country}", Modifier.fillMaxWidth().clickable { viewModel.select(place) }.padding(vertical = 8.dp)) } when { state.isLoading -> Box(Modifier.fillMaxWidth().padding(32.dp), Alignment.Center) { CircularProgressIndicator() } state.error != null -> Text(state.error!!, color = MaterialTheme.colorScheme.error) state.weather != null -> WeatherContent(state.weather!!) else -> Text("Search for a city to see its weather.") } } } @Composable fun WeatherContent(weather: Weather) { Column(Modifier.fillMaxWidth(), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(8.dp)) { Text(weather.place.name, style = MaterialTheme.typography.headlineMedium) Icon(weather.condition.icon, contentDescription = weather.condition.text, modifier = Modifier.size(80.dp), tint = MaterialTheme.colorScheme.primary) Text("${weather.temp}°", fontSize = 64.sp, fontWeight = FontWeight.Light) Text(weather.condition.text, color = MaterialTheme.colorScheme.onSurfaceVariant) Text("Wind ${weather.wind} km/h", style = MaterialTheme.typography.bodySmall) LazyRow(horizontalArrangement = Arrangement.spacedBy(8.dp), contentPadding = PaddingValues(vertical = 16.dp)) { items(weather.hours) { hour -> Card { Column(Modifier.padding(12.dp), horizontalAlignment = Alignment.CenterHorizontally) { Text(hour.label, style = MaterialTheme.typography.labelSmall) Text("${hour.temp}°", style = MaterialTheme.typography.titleMedium) } } } } } }
Concept usedFrom lesson
Retrofit and kotlinx serializationNetworking and JSON
Debounced search with delay and job cancelCoroutines
Single UiState data classViewModel
LazyRow cardsLazy lists
Ideas: Add the device location with the Fused Location client, save favorite cities with Room, show a daily forecast and add a Glance widget.

Conclusion

You combined Retrofit, JSON, a repository, a ViewModel with debounced search and a polished Compose UI.

Quick Summary: Geocode a city, fetch the forecast, map DTOs to app models, keep one UiState in the ViewModel and render cards.

Get Newsletter

Subscibe to our newsletter and we will notify you about the newest updates on Edugators