Getting everything ready for you…

Loading courses, problems and your progress. This takes just a moment.

0s

Android (Jetpack Compose) Documentation

Modern Android apps in Kotlin — Compose layouts, state, ViewModel, navigation, Retrofit, Room and publishing.

Modern Android apps are written in Kotlin with Jetpack Compose, Google's toolkit for building UI in code. This page covers the parts you need to build a real app. New to the language? Start with the Kotlin docs.

1. Introduction

Piece What it does
Android Studio The official IDE, with an emulator
Gradle Builds the app and downloads libraries
Activity An entry point with a screen; most apps need just one
Jetpack Compose Declarative UI: functions describe the screen
ViewModel Keeps screen data alive when the phone rotates
Room Local database
Retrofit Calls REST APIs

2. Project Structure and First App

app/
  src/main/java/com/example/app/MainActivity.kt   → your code
  src/main/res/                                   → icons, strings
  src/main/AndroidManifest.xml                    → permissions, activities
  build.gradle.kts                                → libraries
class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            MaterialTheme {
                Greeting("Codify")
            }
        }
    }
}

@Composable
fun Greeting(name: String) {
    Text(text = "Hello, $name!")
}

@Preview(showBackground = true)
@Composable
fun GreetingPreview() {
    Greeting("Preview")
}

3. Activity Lifecycle

onCreate → onStart → onResume (visible and interactive) → onPause → onStop → onDestroy.

  • Rotating the phone destroys and recreates the Activity by default, which is why data belongs in a ViewModel.
  • Stop heavy work in onPause/onStop, such as location updates.

4. Compose Layouts

Composable Use
Column / Row Vertical / horizontal
Box Stack things on top of each other
LazyColumn / LazyRow Long lists (like RecyclerView, far less code)
Scaffold Top bar, bottom bar, floating button
Spacer Empty space
@Composable
fun StudentList(students: List<Student>) {
    LazyColumn(contentPadding = PaddingValues(16.dp)) {
        items(students, key = { it.id }) { s ->
            Card(modifier = Modifier.fillMaxWidth().padding(vertical = 4.dp)) {
                Column(Modifier.padding(12.dp)) {
                    Text(s.name, style = MaterialTheme.typography.titleMedium)
                    Text("${s.marks} marks")
                }
            }
        }
    }
}

Modifiers style and position things, and their order matters: padding then background is different from background then padding.

5. State in Compose

When state changes, Compose re-runs the functions that read it. This is called recomposition.

@Composable
fun Counter() {
    var count by remember { mutableStateOf(0) }
    Button(onClick = { count++ }) {
        Text("Clicked $count times")
    }
}
  • remember keeps a value across recompositions.
  • rememberSaveable also survives rotation.
  • State hoisting: pass the value down and events up, so composables stay reusable.
@Composable
fun NameField(name: String, onChange: (String) -> Unit) {
    OutlinedTextField(value = name, onValueChange = onChange, label = { Text("Name") })
}

Common mistake: a plain var count = 0 resets on every recomposition, and the screen never updates.

6. ViewModel and StateFlow

data class UiState(val loading: Boolean = false, val posts: List<Post> = emptyList(), val error: String? = null)

class PostsViewModel(private val repo: PostRepository) : ViewModel() {
    private val _state = MutableStateFlow(UiState())
    val state: StateFlow<UiState> = _state.asStateFlow()

    fun load() = viewModelScope.launch {
        _state.update { it.copy(loading = true, error = null) }
        try {
            val posts = repo.getPosts()
            _state.update { it.copy(loading = false, posts = posts) }
        } catch (e: Exception) {
            _state.update { it.copy(loading = false, error = e.message) }
        }
    }
}

@Composable
fun PostsScreen(vm: PostsViewModel) {
    val state by vm.state.collectAsStateWithLifecycle()
    when {
        state.loading -> CircularProgressIndicator()
        state.error != null -> Text("Error: ${state.error}")
        else -> LazyColumn { items(state.posts) { Text(it.title) } }
    }
}

MVVM: the UI shows state and sends events; the ViewModel holds logic; the repository fetches data.

8. Calling an API with Retrofit

interface Api {
    @GET("posts")
    suspend fun getPosts(): List<Post>

    @POST("posts")
    suspend fun create(@Body post: Post): Post
}

val api: Api = Retrofit.Builder()
    .baseUrl("https://jsonplaceholder.typicode.com/")
    .addConverterFactory(GsonConverterFactory.create())
    .build()
    .create(Api::class.java)

Add this to AndroidManifest.xml:

<uses-permission android:name="android.permission.INTERNET" />

Coroutines run slow work without freezing the UI: suspend functions wait without blocking, and viewModelScope cancels them when the screen goes away.

Common mistake: network calls on the main thread crash the app with NetworkOnMainThreadException.

9. Local Storage with Room

@Entity
data class Note(@PrimaryKey(autoGenerate = true) val id: Int = 0, val text: String)

@Dao
interface NoteDao {
    @Query("SELECT * FROM Note ORDER BY id DESC")
    fun all(): Flow<List<Note>>      // updates the UI by itself

    @Insert
    suspend fun add(note: Note)

    @Delete
    suspend fun remove(note: Note)
}

@Database(entities = [Note::class], version = 1)
abstract class AppDb : RoomDatabase() {
    abstract fun notes(): NoteDao
}

For small settings use DataStore (the replacement for SharedPreferences).

10. Permissions, Notifications and Background Work

val launcher = rememberLauncherForActivityResult(ActivityResultContracts.RequestPermission()) { granted ->
    if (granted) { /* use the camera */ }
}
Button(onClick = { launcher.launch(Manifest.permission.CAMERA) }) { Text("Allow camera") }
  • Dangerous permissions (camera, location) must be asked for at runtime and can be refused.
  • Android 13+ also asks for permission to post notifications.
  • Use WorkManager for reliable background jobs, such as a daily sync.

11. Testing and Publishing

@Test
fun addsNumbers() {
    assertEquals(4, 2 + 2)
}
  • Unit tests live in src/test, device tests in src/androidTest.
  • Publish a signed App Bundle (.aab) from Build → Generate Signed App Bundle.
  • A Play Console account costs a one-time $25. Keep your signing key safe.

12. Practice Problems

  1. A counter that survives rotation (ViewModel or rememberSaveable).
  2. A notes app with Room: add, list, delete.
  3. A news app using Retrofit, with loading and error states.
  4. A two-screen app that passes an id with Navigation.
  5. A habit tracker with daily reminders.

13. Interview Questions

Activity vs Fragment? An Activity is an entry point with its own lifecycle; a Fragment is a reusable part of a screen hosted by an Activity. Compose apps often need neither fragments nor many activities.

Why ViewModel? It survives configuration changes like rotation and keeps logic out of the UI.

What is recomposition? Compose re-running composables whose state changed.

remember vs rememberSaveable? remember survives recomposition; rememberSaveable also survives rotation and process death.

LiveData vs StateFlow? Both hold observable state; StateFlow is Kotlin-first, needs an initial value and works with coroutine operators.

What is a coroutine? A lightweight task that can pause without blocking a thread.

What is an ANR? "Application Not Responding" — the main thread was blocked for too long.

What is an Intent? A message to start a component, such as opening another app or sharing text.

What are the four app components? Activity, Service, BroadcastReceiver and ContentProvider.

14. Cheat Sheet & References

Compose basics

@Composable fun Screen() { }
Column { } / Row { } / Box { }
LazyColumn { items(list) { Text(it) } }
Text("Hi") / Button(onClick = { }) { Text("OK") }
Modifier.fillMaxWidth().padding(16.dp)

State

var x by remember { mutableStateOf(0) }
var y by rememberSaveable { mutableStateOf("") }
val s by vm.state.collectAsStateWithLifecycle()

Architecture

UI (Compose) → ViewModel (StateFlow) → Repository → Retrofit / Room
Lifecycle: onCreate → onStart → onResume → onPause → onStop → onDestroy

References