gradle/libs.versions.tomlPinned for Kotlin 2.0.21. Don't accept "newer version" hints. Set lifecycleRuntimeKtx = "2.8.7".
[versions]
lifecycle = "2.8.7"
navigationCompose = "2.8.9"
retrofit = "2.11.0"
okhttp = "4.12.0"
coil = "3.0.4"
[libraries]
androidx-lifecycle-viewmodel-compose = { group = "androidx.lifecycle", name = "lifecycle-viewmodel-compose", version.ref = "lifecycle" }
androidx-lifecycle-runtime-compose = { group = "androidx.lifecycle", name = "lifecycle-runtime-compose", version.ref = "lifecycle" }
androidx-navigation-compose = { group = "androidx.navigation", name = "navigation-compose", version.ref = "navigationCompose" }
androidx-compose-material-icons-extended = { group = "androidx.compose.material", name = "material-icons-extended" }
retrofit = { group = "com.squareup.retrofit2", name = "retrofit", version.ref = "retrofit" }
retrofit-converter-gson = { group = "com.squareup.retrofit2", name = "converter-gson", version.ref = "retrofit" }
okhttp-logging = { group = "com.squareup.okhttp3", name = "logging-interceptor", version.ref = "okhttp" }
coil-compose = { group = "io.coil-kt.coil3", name = "coil-compose", version.ref = "coil" }
coil-network-okhttp = { group = "io.coil-kt.coil3", name = "coil-network-okhttp", version.ref = "coil" }
app/build.gradle.kts → dependencies { }implementation(libs.androidx.lifecycle.viewmodel.compose)
implementation(libs.androidx.lifecycle.runtime.compose)
implementation(libs.androidx.navigation.compose)
implementation(libs.androidx.compose.material.icons.extended)
implementation(libs.retrofit)
implementation(libs.retrofit.converter.gson)
implementation(libs.okhttp.logging)
implementation(libs.coil.compose)
implementation(libs.coil.network.okhttp) // Coil 3 shows nothing for URLs without this
AndroidManifest.xml (above <application>)<uses-permission android:name="android.permission.INTERNET" />
<!-- only if forced onto http://, add to <application>: android:usesCleartextTraffic="true" -->
git tag skeleton # once
git reset --hard skeleton && git clean -fd
.gitignore should include .kotlin and .idea.
com.example.skeleton/
├── MainActivity.kt ← setContent, theme, Scaffold, NavHost. No data.
├── data/
│ ├── ApiClient.kt ← Retrofit + OkHttp
│ ├── User.kt ← models (data classes)
│ ├── UserApi.kt ← Retrofit interface
│ └── UserRepository.kt ← single source of data
└── ui/
├── UiState.kt
├── theme/
├── list/ ListViewModel.kt, ListScreen.kt
└── detail/ DetailViewModel.kt, DetailScreen.kt
import androidx.compose.foundation.* // clickable, background, Image
import androidx.compose.foundation.layout.* // Row, Column, Box, Spacer, padding, size, width, fillMaxWidth
import androidx.compose.foundation.lazy.* // LazyColumn, items, item
import androidx.compose.material3.* // Text, Button, Scaffold, TopAppBar, MaterialTheme, FilterChip
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.* // Icons.Filled.Search, Star, Refresh
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.runtime.* // Composable, remember, mutableStateOf, getValue, setValue, LaunchedEffect
import androidx.compose.ui.* // Modifier, Alignment
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.* // dp, sp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewmodel.compose.viewModel
import coil3.compose.AsyncImage
ViewModel files: androidx.lifecycle.ViewModel, androidx.lifecycle.viewModelScope, kotlinx.coroutines.flow.*, kotlinx.coroutines.launch, kotlinx.coroutines.delay, kotlinx.coroutines.isActive.
Retrofit: retrofit2.http.GET, retrofit2.http.Path, retrofit2.http.Query, retrofit2.HttpException. Gson: com.google.gson.annotations.SerializedName.
Every problem is this template with a different model and endpoint.
data/ApiClient.ktpackage com.example.skeleton.data
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
object ApiClient {
private val logging = HttpLoggingInterceptor().apply {
level = HttpLoggingInterceptor.Level.BODY // full JSON in Logcat
}
private val client = OkHttpClient.Builder().addInterceptor(logging).build()
fun retrofit(baseUrl: String): Retrofit = Retrofit.Builder()
.baseUrl(baseUrl) // MUST end with "/"
.client(client)
.addConverterFactory(GsonConverterFactory.create())
.build()
}
ui/UiState.ktpackage com.example.skeleton.ui
sealed interface UiState<out T> {
data object Loading : UiState<Nothing>
data class Success<T>(val data: T) : UiState<T>
data class Error(val message: String) : UiState<Nothing>
}
data/)data class User(
val id: Int,
val name: String,
val email: String,
val company: Company
)
data class Company(val name: String)
interface UserApi {
@GET("users")
suspend fun getUsers(): List<User>
@GET("users/{id}/posts")
suspend fun getPosts(@Path("id") userId: Int): List<Post>
}
class UserRepository {
private val api: UserApi = ApiClient
.retrofit("https://jsonplaceholder.typicode.com/")
.create(UserApi::class.java)
suspend fun getUsers(): List<User> = api.getUsers()
suspend fun getPosts(userId: Int): List<Post> = api.getPosts(userId)
}
class UserListViewModel : ViewModel() {
private val repository = UserRepository()
private val _state = MutableStateFlow<UiState<List<User>>>(UiState.Loading)
val state: StateFlow<UiState<List<User>>> = _state.asStateFlow()
init { load() } // once; rotation reuses this ViewModel
fun load() {
_state.value = UiState.Loading
viewModelScope.launch {
_state.value = try {
UiState.Success(repository.getUsers())
} catch (e: Exception) {
UiState.Error(e.message ?: "Something went wrong")
}
}
}
}
@Composable
fun UserListScreen(
onUserClick: (Int) -> Unit,
modifier: Modifier = Modifier,
viewModel: UserListViewModel = viewModel()
) {
val state by viewModel.state.collectAsStateWithLifecycle()
Box(modifier = modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
when (val s = state) { // local val → smart cast works
UiState.Loading -> CircularProgressIndicator()
is UiState.Error -> ErrorView(s.message, onRetry = viewModel::load)
is UiState.Success ->
if (s.data.isEmpty()) Text("No users")
else LazyColumn(Modifier.fillMaxSize()) {
items(s.data, key = { it.id }) { user ->
UserRow(user, Modifier.clickable { onUserClick(user.id) })
HorizontalDivider()
}
}
}
}
}
@Composable
fun UserRow(user: User, modifier: Modifier = Modifier) {
Column(modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 12.dp)) {
Text(user.name, fontWeight = FontWeight.Bold)
Text(user.email, style = MaterialTheme.typography.bodySmall)
Text(user.company.name, style = MaterialTheme.typography.bodySmall)
}
}
@Composable
fun ErrorView(message: String, onRetry: () -> Unit) {
Column(horizontalAlignment = Alignment.CenterHorizontally) {
Text(message)
Spacer(Modifier.height(8.dp))
Button(onClick = onRetry) { Text("Retry") }
}
}
@Composable
fun StockRow(stock: Stock, modifier: Modifier = Modifier) {
Row(
modifier = modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 12.dp),
verticalAlignment = Alignment.CenterVertically
) {
AsyncImage(model = stock.url, contentDescription = stock.name, modifier = Modifier.size(32.dp))
Spacer(Modifier.width(12.dp))
Column {
Text(stock.symbol, fontWeight = FontWeight.Bold)
Text(stock.name, style = MaterialTheme.typography.bodySmall)
}
Spacer(Modifier.weight(1f)) // pushes the price to the right edge
Column(horizontalAlignment = Alignment.End) {
Text("$" + "%.2f".format(stock.price))
Text(
(if (stock.change >= 0) "+" else "") + "%.2f%%".format(stock.change),
color = if (stock.change >= 0) Color(0xFF00C805) else Color.Red
)
}
}
}
| JSON looks like | Kotlin |
|---|---|
[ {...}, {...} ] (top-level array) | suspend fun get(): List<Item> |
{ "results": [ ... ] } (wrapped) | data class Resp(val results: List<Item>) → suspend fun get(): Resp |
"current_price": 1.2 (snake_case) | @SerializedName("current_price") val currentPrice: Double |
"quotes": { "USD": { "price": 1 } } | One data class per object level; @SerializedName("USD") val usd: UsdQuote |
| Field sometimes null or missing | Make it nullable: val change: Double? (Gson leaves null even in non-null fields) |
"lat": "-37.31" (number as string) | val lat: String, then lat.toDoubleOrNull() |
| Fields you don't need | Leave them out. Gson ignores undeclared keys. |
?vs_currency=usd | @Query("vs_currency") currency: String = "usd" |
/users/{id}/posts | @GET("users/{id}/posts") suspend fun posts(@Path("id") id: Int) |
Models use val, never var. To change one, make a new object with copy() so the StateFlow emits.
enum class SortOrder { RANK, PRICE, CHANGE }
class CoinListViewModel : ViewModel() {
private val repository = CoinRepository()
private val _state = MutableStateFlow<UiState<List<Coin>>>(UiState.Loading)
private val _query = MutableStateFlow("")
private val _sort = MutableStateFlow(SortOrder.RANK)
val query: StateFlow<String> = _query.asStateFlow()
val sort: StateFlow<SortOrder> = _sort.asStateFlow()
// What the screen shows = fetched data + query + sort
val visible: StateFlow<UiState<List<Coin>>> =
combine(_state, _query, _sort) { state, q, sort ->
if (state !is UiState.Success) state
else UiState.Success(
state.data
.filter { q.isBlank() || it.name.contains(q, true) || it.symbol.contains(q, true) }
.let { list ->
when (sort) {
SortOrder.RANK -> list.sortedBy { it.rank }
SortOrder.PRICE -> list.sortedByDescending { it.price }
SortOrder.CHANGE -> list.sortedByDescending { it.change }
}
}
)
}.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), UiState.Loading)
fun onQueryChange(q: String) { _query.value = q }
fun onSortChange(s: SortOrder) { _sort.value = s }
init { load() }
fun load() { /* same as the core template, writing to _state */ }
}
// Screen: search field + chips above the list
val query by viewModel.query.collectAsStateWithLifecycle()
val sort by viewModel.sort.collectAsStateWithLifecycle()
Column(modifier.fillMaxSize()) {
OutlinedTextField(
value = query, // what the field shows
onValueChange = viewModel::onQueryChange, // called with the new text on every keystroke
label = { Text("Search") },
leadingIcon = { Icon(Icons.Filled.Search, contentDescription = null) },
singleLine = true,
modifier = Modifier.fillMaxWidth().padding(16.dp)
)
Row(Modifier.padding(horizontal = 16.dp), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
SortOrder.entries.forEach { option ->
FilterChip(
selected = sort == option,
onClick = { viewModel.onSortChange(option) },
label = { Text(option.name.lowercase().replaceFirstChar { it.uppercase() }) }
)
}
}
// then the Box + when(visible) block; empty Success → Text("No coins match \"$query\"")
}
The error state shows Button(onClick = viewModel::load). Test with airplane mode.
@OptIn(ExperimentalMaterial3Api::class)
PullToRefreshBox(
isRefreshing = isRefreshing, // separate StateFlow<Boolean>
onRefresh = viewModel::refresh
) { LazyColumn { ... } }
Keep the old list while refreshing. Don't switch to Loading.
init {
viewModelScope.launch {
while (isActive) { load(); delay(30_000) }
}
}
It stops automatically when the ViewModel is cleared.
private val _favs = MutableStateFlow<Set<String>>(emptySet())
fun toggleFav(id: String) =
_favs.update { if (id in it) it - id else it + id }
// in combine: .sortedByDescending { it.id in favs }
val time = SimpleDateFormat("HH:mm", Locale.US).format(Date())
LazyColumn { item { Text("Updated $time") } ; items(...) }
} catch (e: HttpException) {
UiState.Error(if (e.code() == 429)
"Rate limited (429). Try again in a minute."
else "Server error ${e.code()}")
} catch (e: Exception) { ... }
Put HttpException before Exception.
data class Quote(val symbol: String, val price: Double, val previous: Double)
class TickerViewModel : ViewModel() {
private val _quotes = MutableStateFlow(
listOf("AAPL", "NVDA", "HOOD", "TSLA", "AMZN").map { Quote(it, 100.0, 100.0) }
)
val quotes: StateFlow<List<Quote>> = _quotes.asStateFlow()
private val _running = MutableStateFlow(false)
val running: StateFlow<Boolean> = _running.asStateFlow()
private var job: Job? = null
init { start() }
fun start() {
if (job?.isActive == true) return // never two loops
_running.value = true
job = viewModelScope.launch {
while (isActive) {
delay(1_000)
_quotes.update { list ->
list.map { q ->
q.copy(previous = q.price,
price = q.price * (1 + Random.nextDouble(-0.01, 0.01)))
}
}
}
}
}
fun pause() { job?.cancel(); _running.value = false }
}
// Row color
val color = when {
q.price > q.previous -> Color(0xFF00C805)
q.price < q.previous -> Color.Red
else -> MaterialTheme.colorScheme.onSurface
}
// List: items(quotes, key = { it.symbol }) { ... } ← stable keys, no flicker
// Button: if (running) Button(viewModel::pause) { Text("Pause") } else Button(viewModel::start) { Text("Resume") }
Alerts extension: store targets: Map<String, Double> and an alerted: Set<String>. In the loop, when the price crosses the target and the symbol isn't in alerted, emit to a MutableSharedFlow<String>. The screen collects it in LaunchedEffect(Unit) and calls snackbarHostState.showSnackbar(msg).
Imports: kotlinx.coroutines.Job, kotlinx.coroutines.flow.update, kotlin.random.Random.
data class Timer(val id: Int, val remaining: Int, val running: Boolean = true)
class TimersViewModel : ViewModel() {
private var nextId = 0
private val _timers = MutableStateFlow<List<Timer>>(emptyList())
val timers: StateFlow<List<Timer>> = _timers.asStateFlow()
init {
viewModelScope.launch { // ONE loop ticks every running timer
while (isActive) {
delay(1_000)
_timers.update { list ->
list.map { if (it.running && it.remaining > 0) it.copy(remaining = it.remaining - 1) else it }
}
}
}
}
fun add() = _timers.update { it + Timer(nextId++, 30) }
fun remove(id: Int) = _timers.update { list -> list.filterNot { it.id == id } }
fun toggle(id: Int) = _timers.update { list ->
list.map { if (it.id == id) it.copy(running = !it.running) else it }
}
}
// Row text: if (t.remaining == 0) "Done" else "${t.remaining}s"
Each one is the core template plus the differences listed here.
lifecycleRuntimeKtx = "2.8.7", and sync.data class Stock(val symbol: String, val name: String, val url: String, val price: Double, val change: Double)
class StockRepository {
fun getStocks(): List<Stock> = listOf(
Stock("AAPL", "Apple", "", 187.42, 1.20),
Stock("HOOD", "Robinhood", "", 40.10, -0.85),
Stock("NVDA", "Nvidia", "", 300.00, 2.30),
Stock("TSLA", "Tesla", "", 250.00, -3.10),
Stock("GOOGL", "Google", "", 170.00, 0.40)
)
}
class WatchlistViewModel : ViewModel() {
private val repository = StockRepository()
private val _stocks = MutableStateFlow<List<Stock>>(emptyList())
val stocks: StateFlow<List<Stock>> = _stocks.asStateFlow()
init { _stocks.value = repository.getStocks() }
}
Screen: LazyColumn(modifier = modifier) { items(stocks, key = { it.symbol }) { StockRow(it); HorizontalDivider() } }, using the StockRow above (green/red change = the surprise extension).
Pitfalls: pass the Scaffold padding into the LazyColumn, never offset. Give AsyncImage a size.
API https://jsonplaceholder.typicode.com/users. This is exactly the core template.
Empty-state extension: choose before building the list. if (s.data.isEmpty()) Text("No users") else LazyColumn { ... }. Calling a composable directly inside LazyColumn { } fails, so wrap it in item { } or decide outside.
data class Ticker(
val id: String, val name: String, val symbol: String, val rank: Int,
val quotes: Quotes
)
data class Quotes(@SerializedName("USD") val usd: UsdQuote)
data class UsdQuote(
val price: Double,
@SerializedName("percent_change_24h") val change24h: Double,
@SerializedName("market_cap") val marketCap: Double
)
interface PaprikaApi {
@GET("v1/tickers") suspend fun getTickers(): List<Ticker>
@GET("v1/tickers/{id}") suspend fun getTicker(@Path("id") id: String): Ticker
}
// base URL: "https://api.coinpaprika.com/"
// ViewModel: UiState.Success(repository.getTickers().sortedBy { it.rank }.take(50))
// Row: ticker.quotes.usd.price, ticker.quotes.usd.change24h
Extension: a header with the fetch time (see Timestamp header).
data class Coin(
val id: String, val symbol: String, val name: String, val image: String,
@SerializedName("current_price") val currentPrice: Double,
@SerializedName("price_change_percentage_24h") val change24h: Double? // sometimes null
)
interface GeckoApi {
@GET("api/v3/coins/markets")
suspend fun getMarkets(
@Query("vs_currency") currency: String = "usd",
@Query("per_page") perPage: Int = 50
): List<Coin>
}
// base URL: "https://api.coingecko.com/" · keyless ≈ 5 calls/min → expect 429
// Row: AsyncImage(coin.image, coin.name, Modifier.size(32.dp)); coin.symbol.uppercase()
// change text: coin.change24h?.let { "%.2f%%".format(it) } ?: "—"
data class Post(val id: Int, val userId: Int, val title: String, val body: String)
// UserApi: @GET("users/{id}/posts") suspend fun getPosts(@Path("id") userId: Int): List<Post>
Use the NavHost + UserDetailViewModel(SavedStateHandle) above. Show phone, website and city from the shared list ViewModel (or add phone, website and address.city to User), with the posts below.
Extension: route "post/{postId}" → @GET("posts/{id}") showing body.
data class PokemonListResponse(val results: List<PokemonEntry>)
data class PokemonEntry(val name: String, val url: String) {
val number: Int get() = url.trimEnd('/').substringAfterLast('/').toInt()
}
data class PokemonDetail(
val name: String, val height: Int, val weight: Int,
val sprites: Sprites, val types: List<TypeSlot>
)
data class Sprites(@SerializedName("front_default") val frontDefault: String?)
data class TypeSlot(val type: NamedRef)
data class NamedRef(val name: String)
interface PokeApi {
@GET("pokemon") suspend fun getList(@Query("limit") limit: Int = 151): PokemonListResponse
@GET("pokemon/{name}") suspend fun getPokemon(@Path("name") name: String): PokemonDetail
}
// base URL: "https://pokeapi.co/api/v2/"
// list: repository returns api.getList().results
// route: "detail/{name}" with NavType.StringType; detail VM reads savedStateHandle["name"]
// display: name.replaceFirstChar { it.uppercase() }, types.joinToString { it.type.name }
// AsyncImage(model = detail.sprites.frontDefault, ...)
See Extensions. Talk track: "I keep the fetched data untouched and derive the visible list, so search, sort and refresh don't fight each other."
See Live-updating lists. What they're probing: state lives in the ViewModel, rows use stable keys, and coroutines are cancelled properly.
CoinPaprika list (2B) → detail/{id} with getTicker(id) showing rank, price, 24h change and market cap → search (4A).
Surprise: refresh every 15 s without losing the search. The 4E loop writes to _state, and combine keeps _query applied.
Follow-ups: "Why pass the id?" (small, survives process death, and the detail screen can refetch). "Rotation?" (the ViewModel survives). "10,000 assets?" (paging, server-side search, stable keys).
data class Post(val id: Int, val title: String, val body: String)
data class Comment(val id: Int, val name: String, val email: String, val body: String)
interface PostApi {
@GET("posts") suspend fun getPosts(): List<Post>
@GET("posts/{id}") suspend fun getPost(@Path("id") id: Int): Post
@GET("posts/{id}/comments") suspend fun getComments(@Path("id") id: Int): List<Comment>
}
// preview text: Text(post.body, maxLines = 2, overflow = TextOverflow.Ellipsis)
Surprise "mark as read": keep a MutableStateFlow<Set<Int>> in an Activity-scoped ViewModel and draw read rows with Modifier.alpha(0.5f) (import androidx.compose.ui.draw.alpha). "Across restarts?" → DataStore or Room.
data class Country(
val name: CountryName, val flags: Flags, val region: String,
val population: Long, val capital: List<String>?, val cca3: String
)
data class CountryName(val common: String)
data class Flags(val png: String)
interface CountryApi {
@GET("v3.1/all")
suspend fun getAll(
@Query("fields") fields: String = "name,flags,region,population,capital,cca3" // required
): List<Country>
}
// base URL: "https://restcountries.com/" · key = { it.cca3 } · route "detail/{cca3}"
fun formatPopulation(n: Long): String = when {
n >= 1_000_000_000 -> "%.1fB".format(n / 1e9)
n >= 1_000_000 -> "%.1fM".format(n / 1e6)
n >= 1_000 -> "%.1fK".format(n / 1e3)
else -> n.toString()
}
// capital: country.capital?.firstOrNull() ?: "No capital"
// region chips: data.map { it.region }.distinct().sorted() → FilterChip; filter in combine
| Need | Use |
|---|---|
| Vertical / horizontal / layered | Column / Row / Box |
| Push to far edge | Spacer(Modifier.weight(1f)) (only inside Row/Column) |
| Gap | Spacer(Modifier.width(12.dp)) or Arrangement.spacedBy(8.dp) |
| Center children | Row: verticalAlignment = Alignment.CenterVertically · Column: horizontalAlignment = Alignment.CenterHorizontally · Box: contentAlignment = Alignment.Center |
| Scrolling list | LazyColumn { items(list, key = { it.id }) { ... } } · single row: item { } |
| Tap | Modifier.clickable { } (put it before padding so the padding is tappable) |
| Image from URL | AsyncImage(model = url, contentDescription = name, modifier = Modifier.size(40.dp)) |
| Text input | OutlinedTextField(value = q, onValueChange = onQ, label = { Text("Search") }, singleLine = true) |
| Truncate | Text(s, maxLines = 2, overflow = TextOverflow.Ellipsis) |
| Loading | CircularProgressIndicator() |
| Card row | Card(Modifier.fillMaxWidth().padding(8.dp)) { ... } |
| Local UI state | var x by remember { mutableStateOf(false) } · survives rotation: rememberSaveable |
| ViewModel state | val s by vm.state.collectAsStateWithLifecycle() |
| Run once / on key change | LaunchedEffect(key) { ... } |
| Theme values | MaterialTheme.typography.bodySmall, MaterialTheme.colorScheme.primary |
| Experimental API error | @OptIn(ExperimentalMaterial3Api::class) (TopAppBar, PullToRefreshBox) |
Rules: UI = f(state). Composables return nothing and can only be called from composables. Data flows down; events flow up as lambdas. No fetching or list-building inside composables. Every composable takes modifier: Modifier = Modifier.
list.filter { it.price > 0 } list.map { it.name } list.find { it.id == id }
list.sortedBy { it.rank } list.sortedByDescending { it.price }
list.take(50) list.distinct() list.groupBy { it.region }
list.any { } list.all { } list.count { } list.sumOf { it.price } list.joinToString { it.name }
list.firstOrNull() list + item set - item list.filterNot { }
s.contains(q, ignoreCase = true) s.replaceFirstChar { it.uppercase() } s.uppercase()
s.substringAfterLast('/') s.trimEnd('/') s.toIntOrNull() s.toDoubleOrNull()
"%.2f".format(x) "$" + "%.2f".format(price) "%.1fM".format(n / 1e6)
a ?: b // b if a is null
a?.b // null if a is null
x as? Type // null if not that type
obj.copy(price = 1.0) // data class: new object, one field changed
when (val s = state) { is X -> ...; else -> ... }
viewModel::load // function reference = { viewModel.load() }
| You see | Fix |
|---|---|
Unresolved reference (Row, width, padding, getValue) | Missing import. Use Alt+Enter and pick the androidx.compose one. Extension functions like width need their own import. |
| @Composable invocations can only happen from a @Composable function | A composable was called inside LazyColumn { } or onClick = { }. Wrap it in item { }, or change state instead. |
| Property delegate must have a getValue method | import androidx.compose.runtime.getValue |
| This API is experimental | @OptIn(ExperimentalMaterial3Api::class) |
Smart cast impossible on state | when (val s = state) |
UnknownHostException / SecurityException | INTERNET permission missing. Add it and reinstall the app. |
| Cleartext HTTP traffic not permitted | Use https, or android:usesCleartextTraffic="true" |
| baseUrl must end in / | Add the trailing / |
| Expected BEGIN_ARRAY but was BEGIN_OBJECT | The JSON is wrapped. Add data class Resp(val results: List<T>) |
| Expected BEGIN_OBJECT but was BEGIN_ARRAY | The opposite: return List<T> |
| Field shows null or blank | Name mismatch. Use @SerializedName("json_name") and check Logcat. |
| NullPointerException on a model field | JSON had null. Make the field nullable (?) and use ?: "—" |
NetworkOnMainThreadException | Make the API function suspend and call it in viewModelScope.launch |
| Endless requests in Logcat | Loading was called from the composable body. Move it to the ViewModel init. |
| List resets on rotation | State was in remember or the Activity. Move it to the ViewModel. |
| Content under the status bar | Pass Modifier.padding(innerPadding) to the content |
| Image blank | Missing coil-network-okhttp, or the URL is null |
| LazyColumn crash: infinite height | Don't nest it inside Column(Modifier.verticalScroll()) |
| Typing does nothing in a text field | onValueChange must update the state that feeds value |
| UI doesn't update after a change | An object was mutated in place. Use a val model + copy() and assign a new list. |
| Local server unreachable from the emulator | Use 10.0.2.2, not localhost |
| HTTP 429 | Rate limited. Catch HttpException, show a message, wait before retrying. |