Skip to content

Practical Android App Development Interview Questions

42 questions with answers. Hands-on questions where you write code, a query, a formula or concrete steps.

How to approach these questions

Talk while you work: say your approach first, write the simplest correct version, then improve it and mention edge cases.

Solved — practicalStart practicing
3 QUESTIONS FREESign up to unlock the full question bank and track your progress.Unlock every question and answer, then continue practising company-wise and package-wise.
3 questions free Unlock the rest in seconds
01

Write a sealed interface for a screen state and handle it with when.

Save to ▾
Show answer
sealed interface UiState { data object Loading : UiState data class Success(val items: List<String>) : UiState data class Error(val message: String) : UiState } fun render(state: UiState) = when (state) { UiState.Loading -> showProgress() is UiState.Success -> showList(state.items) is UiState.Error -> showError(state.message) }
02

Write a Kotlin function that groups a list of orders by city and returns total amount per city.

Save to ▾
Show answer
data class Order(val city: String, val amount: Double) fun totalsByCity(orders: List<Order>): Map<String, Double> = orders.groupBy { it.city } .mapValues { (_, list) -> list.sumOf { it.amount } } // Alternative with one pass: // orders.groupingBy { it.city }.fold(0.0) { acc, o -> acc + o.amount }
03

Write a delegated property that logs whenever a value changes.

Save to ▾
Show answer
import kotlin.properties.Delegates class Settings { var theme: String by Delegates.observable("light") { prop, old, new -> println("${prop.name} changed from $old to $new") } } // Use Delegates.vetoable if you need to reject a change // by returning false from the lambda.
04

Write a function that safely parses a string to an Int and returns a default on failure.

Save to ▾
Show answer
fun String?.toIntOrDefault(default: Int = 0): Int = this?.trim()?.toIntOrNull() ?: default // Usage val qty = input.text.toString().toIntOrDefault(1) val age = null.toIntOrDefault() // 0
05

Write code to fetch two API results in parallel inside a ViewModel.

Save to ▾
Show answer
fun loadDashboard() { viewModelScope.launch { _state.value = UiState.Loading try { val (profile, orders) = coroutineScope { val p = async { repo.getProfile() } val o = async { repo.getOrders() } p.await() to o.await() } _state.value = UiState.Success(profile, orders) } catch (e: IOException) { _state.value = UiState.Error("Network error") } } }
06

Write a search flow that debounces user input and cancels stale requests.

Save to ▾
Show answer
private val query = MutableStateFlow("") val results: StateFlow<List<Item>> = query .debounce(300) .map { it.trim() } .filter { it.length >= 2 } .distinctUntilChanged() .flatMapLatest { q -> repo.search(q) } .catch { emit(emptyList()) } .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), emptyList()) fun onQueryChange(text: String) { query.value = text }
07

How should a Fragment or Activity collect a Flow safely?

Save to ▾
Show answer
Use lifecycleScope.launch with repeatOnLifecycle(Lifecycle.State.STARTED) so collection starts when the UI is visible and stops in the background, avoiding wasted work and crashes from updating views that are not ready. In a Fragment, use viewLifecycleOwner.lifecycleScope because the fragment view can be destroyed while the fragment lives. In Compose, use collectAsStateWithLifecycle(), which does the same lifecycle-aware collection.
08

Write a suspend function that wraps a callback-based API.

Save to ▾
Show answer
suspend fun FusedLocationProviderClient.awaitLastLocation(): Location? = suspendCancellableCoroutine { cont -> lastLocation .addOnSuccessListener { cont.resume(it) } .addOnFailureListener { cont.resumeWithException(it) } cont.invokeOnCancellation { /* cancel request if supported */ } } // For streams of callbacks, use callbackFlow { } with awaitClose { }.
09

Write a Flow that combines user settings and product list into one UI state.

Save to ▾
Show answer
val uiState: StateFlow<HomeState> = combine( settingsRepo.settings, productRepo.products ) { settings, products -> HomeState( currency = settings.currency, items = products.sortedBy { it.price } ) }.stateIn( scope = viewModelScope, started = SharingStarted.WhileSubscribed(5000), initialValue = HomeState() )
10

How do you unit test a ViewModel that uses coroutines and StateFlow?

Save to ▾
Show answer
Use kotlinx-coroutines-test. Replace Dispatchers.Main with a test dispatcher using Dispatchers.setMain in a JUnit rule, run tests in runTest so delays are skipped with virtual time, and inject dispatchers into repositories instead of hardcoding Dispatchers.IO. For flows, collect values with Turbine or backgroundScope and assert the sequence, such as Loading then Success. Fake repositories make results deterministic.
11

Write code to request camera permission using the Activity Result API.

Save to ▾
Show answer
private val cameraPermission = registerForActivityResult( ActivityResultContracts.RequestPermission() ) { granted -> if (granted) openCamera() else showPermissionDenied() } fun onScanClicked() { when { ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED -> openCamera() shouldShowRequestPermissionRationale(Manifest.permission.CAMERA) -> showRationale { cameraPermission.launch(Manifest.permission.CAMERA) } else -> cameraPermission.launch(Manifest.permission.CAMERA) } }
12

Write a manifest entry for a deep link that opens a product screen.

Save to ▾
Show answer
<activity android:name=".MainActivity" android:exported="true"> <intent-filter android:autoVerify="true"> <action android:name="android.intent.action.VIEW" /> <category android:name="android.intent.category.DEFAULT" /> <category android:name="android.intent.category.BROWSABLE" /> <data android:scheme="https" android:host="shop.example.com" android:pathPrefix="/product" /> </intent-filter> </activity> <!-- autoVerify plus assetlinks.json on the domain makes it an App Link -->
13

Write code to show a notification with a channel.

Save to ▾
Show answer
fun showOrderNotification(context: Context, text: String) { val channelId = "orders" if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { val channel = NotificationChannel( channelId, "Order updates", NotificationManager.IMPORTANCE_DEFAULT) context.getSystemService(NotificationManager::class.java) .createNotificationChannel(channel) } val n = NotificationCompat.Builder(context, channelId) .setSmallIcon(R.drawable.ic_order) .setContentTitle("Order update") .setContentText(text) .setAutoCancel(true) .build() NotificationManagerCompat.from(context).notify(1001, n) }
14

How do you build a single-activity app with the Navigation component?

Save to ▾
Show answer
Keep one Activity hosting a NavHost, and represent each screen as a Compose destination or Fragment. Define routes in a navigation graph, preferably with type-safe routes using Kotlin serialization in Navigation 2.8 and later. Use nested graphs for flows like login or checkout, pop the back stack with popUpTo when finishing a flow, and handle deep links on destinations. This simplifies shared transitions and state handling.
15

Write a stateless text field with a hoisted state and validation message.

Save to ▾
Show answer
@Composable fun EmailField( value: String, onValueChange: (String) -> Unit, error: String?, modifier: Modifier = Modifier ) { OutlinedTextField( value = value, onValueChange = onValueChange, label = { Text("Email") }, isError = error != null, supportingText = { error?.let { Text(it) } }, singleLine = true, modifier = modifier.fillMaxWidth() ) }
16

Write a LazyColumn that shows a list of products with keys and a click handler.

Save to ▾
Show answer
@Composable fun ProductList( products: List<Product>, onClick: (Product) -> Unit ) { LazyColumn( contentPadding = PaddingValues(16.dp), verticalArrangement = Arrangement.spacedBy(8.dp) ) { items(products, key = { it.id }) { product -> ListItem( headlineContent = { Text(product.name) }, supportingContent = { Text("Rs ${product.price}") }, modifier = Modifier.clickable { onClick(product) } ) } } }
17

How do you collect a ViewModel StateFlow in a composable?

Save to ▾
Show answer
Use val state by viewModel.uiState.collectAsStateWithLifecycle() from lifecycle-runtime-compose. It collects only while the lifecycle is at least STARTED, saving resources in the background, unlike collectAsState which keeps collecting. Pass the resulting state and callbacks to a stateless screen composable, which keeps the screen previewable and testable without a ViewModel. Obtain the ViewModel with hiltViewModel() or viewModel() at the route level.
18

How do you implement theming with Material 3 in Compose?

Save to ▾
Show answer
Wrap the app in a MaterialTheme with a ColorScheme, Typography and Shapes. Use lightColorScheme and darkColorScheme, pick based on isSystemInDarkTheme(), and use dynamicLightColorScheme or dynamicDarkColorScheme on Android 12 and above for Material You colours. Components read MaterialTheme.colorScheme.primary and similar roles, so avoid hardcoding colours. Extend the theme with a custom CompositionLocal for brand-specific tokens.
19

How do you test a Compose UI?

Save to ▾
Show answer
Use the Compose testing APIs with createComposeRule or createAndroidComposeRule. Find nodes by text, content description or testTag, then perform actions and assertions, like onNodeWithText("Login").performClick() and onNodeWithTag("error").assertIsDisplayed(). Test stateless composables with fake state for speed. Tests synchronise with Compose automatically. Screenshot testing tools like Roborazzi or Paparazzi catch visual regressions without a device.
20

Write a Compose UI test that checks an error appears when login is clicked with an empty email.

Save to ▾
Show answer
@get:Rule val rule = createComposeRule() @Test fun showsErrorForEmptyEmail() { rule.setContent { var state by remember { mutableStateOf(LoginState()) } LoginScreen( state = state, onLogin = { state = state.copy(error = "Email required") } ) } rule.onNodeWithText("Login").performClick() rule.onNodeWithText("Email required").assertIsDisplayed() }
21

How do you build an adaptive layout for phones, foldables and tablets in Compose?

Save to ▾
Show answer
Use WindowSizeClass from the Material 3 adaptive library to choose layouts by width class, not device type. On compact width show a bottom navigation bar; on medium use a navigation rail; on expanded use a list-detail layout with ListDetailPaneScaffold or NavigationSuiteScaffold. Avoid locking orientation, since Android 16 ignores orientation restrictions on large screens. Test with resizable emulators and foldable postures.
22

Write a Hilt module that provides Retrofit and a repository binding.

Save to ▾
Show answer
@Module @InstallIn(SingletonComponent::class) object NetworkModule { @Provides @Singleton fun provideRetrofit(): Retrofit = Retrofit.Builder() .baseUrl("https://api.example.com/") .addConverterFactory(Json.asConverterFactory("application/json".toMediaType())) .build() @Provides @Singleton fun provideApi(retrofit: Retrofit): ShopApi = retrofit.create(ShopApi::class.java) } @Module @InstallIn(SingletonComponent::class) abstract class RepoModule { @Binds abstract fun bindRepo(impl: ProductRepositoryImpl): ProductRepository }
23

Write a HiltViewModel that exposes a single UiState using StateFlow.

Save to ▾
Show answer
data class ProductUiState( val loading: Boolean = true, val items: List<Product> = emptyList(), val error: String? = null ) @HiltViewModel class ProductViewModel @Inject constructor( private val repo: ProductRepository ) : ViewModel() { private val _state = MutableStateFlow(ProductUiState()) val state: StateFlow<ProductUiState> = _state.asStateFlow() init { refresh() } fun refresh() = viewModelScope.launch { _state.update { it.copy(loading = true, error = null) } runCatching { repo.fetchProducts() } .onSuccess { list -> _state.update { it.copy(loading = false, items = list) } } .onFailure { _state.update { it.copy(loading = false, error = "Try again") } } } }
24

Write a use case that combines cart items and a coupon into a final total.

Save to ▾
Show answer
class GetCartTotalUseCase @Inject constructor( private val cartRepo: CartRepository, private val couponRepo: CouponRepository ) { operator fun invoke(): Flow<Double> = combine(cartRepo.items, couponRepo.activeCoupon) { items, coupon -> val subtotal = items.sumOf { it.price * it.qty } val discount = coupon?.let { minOf(subtotal * it.percent / 100, it.maxOff) } ?: 0.0 subtotal - discount } }
25

How do you handle one-time navigation after a successful login in MVVM?

Save to ▾
Show answer
Recommended practice is to reflect the result in state, such as isLoggedIn = true in UiState, and have the UI react with LaunchedEffect(state.isLoggedIn) to navigate, then the ViewModel marks it consumed if needed. An alternative is a Channel exposed as Flow and collected with lifecycle awareness. Avoid calling navigation directly from the ViewModel, because it should not reference NavController or views.
26

Write a Room entity and DAO for notes with a Flow query.

Save to ▾
Show answer
@Entity(tableName = "notes") data class NoteEntity( @PrimaryKey(autoGenerate = true) val id: Long = 0, val title: String, val body: String, val updatedAt: Long ) @Dao interface NoteDao { @Query("SELECT * FROM notes ORDER BY updatedAt DESC") fun observeAll(): Flow<List<NoteEntity>> @Upsert suspend fun upsert(note: NoteEntity) @Query("DELETE FROM notes WHERE id = :id") suspend fun delete(id: Long) }
27

Write code to save and read a dark mode preference with Preferences DataStore.

Save to ▾
Show answer
val Context.dataStore by preferencesDataStore(name = "settings") private val DARK_MODE = booleanPreferencesKey("dark_mode") class SettingsRepository(private val context: Context) { val darkMode: Flow<Boolean> = context.dataStore.data .catch { emit(emptyPreferences()) } .map { it[DARK_MODE] ?: false } suspend fun setDarkMode(enabled: Boolean) { context.dataStore.edit { it[DARK_MODE] = enabled } } }
28

Write a periodic sync job with WorkManager that runs only on unmetered network.

Save to ▾
Show answer
class SyncWorker(ctx: Context, params: WorkerParameters) : CoroutineWorker(ctx, params) { override suspend fun doWork(): Result = try { repo.sync() Result.success() } catch (e: IOException) { if (runAttemptCount < 3) Result.retry() else Result.failure() } } val request = PeriodicWorkRequestBuilder<SyncWorker>(6, TimeUnit.HOURS) .setConstraints(Constraints(requiredNetworkType = NetworkType.UNMETERED)) .setBackoffCriteria(BackoffPolicy.EXPONENTIAL, 30, TimeUnit.SECONDS) .build() WorkManager.getInstance(context).enqueueUniquePeriodicWork( "sync", ExistingPeriodicWorkPolicy.KEEP, request)
29

How do you write tests for a Room DAO?

Save to ▾
Show answer
Create an in-memory database with Room.inMemoryDatabaseBuilder in an instrumented test or with Robolectric, get the DAO, insert test data and assert query results. For Flow queries, collect the first value with first() or use Turbine. Close the database in @After. Test edge cases like conflict strategies and ordering. In-memory databases are fast and isolated, so each test starts clean.
30

How do you migrate from SharedPreferences to DataStore without losing user data?

Save to ▾
Show answer
Use SharedPreferencesMigration when creating the DataStore: preferencesDataStore(name = "settings", produceMigrations = { ctx -> listOf(SharedPreferencesMigration(ctx, "old_prefs")) }). On first access, DataStore copies the values and deletes the old file. Update all reads and writes to go through the new repository at once, because mixing both stores leads to inconsistent values. Test the migration with existing preference files.
31

Write a Room database class with a migration that adds a column.

Save to ▾
Show answer
@Database(entities = [NoteEntity::class], version = 2, exportSchema = true) abstract class AppDatabase : RoomDatabase() { abstract fun noteDao(): NoteDao } val MIGRATION_1_2 = object : Migration(1, 2) { override fun migrate(db: SupportSQLiteDatabase) { db.execSQL("ALTER TABLE notes ADD COLUMN pinned INTEGER NOT NULL DEFAULT 0") } } val db = Room.databaseBuilder(context, AppDatabase::class.java, "app.db") .addMigrations(MIGRATION_1_2) .build()
32

Write a Retrofit interface for listing products with paging and fetching one product.

Save to ▾
Show answer
interface ShopApi { @GET("products") suspend fun getProducts( @Query("page") page: Int, @Query("size") size: Int = 20 ): ProductPageDto @GET("products/{id}") suspend fun getProduct(@Path("id") id: String): Response<ProductDto> @POST("cart") suspend fun addToCart(@Body body: AddToCartRequest): CartDto }
33

Write an OkHttp interceptor that adds a bearer token to every request.

Save to ▾
Show answer
class AuthInterceptor @Inject constructor( private val tokenStore: TokenStore ) : Interceptor { override fun intercept(chain: Interceptor.Chain): Response { val token = tokenStore.currentAccessToken() val request = chain.request().newBuilder().apply { if (token != null) header("Authorization", "Bearer $token") }.build() return chain.proceed(request) } } val client = OkHttpClient.Builder() .addInterceptor(authInterceptor) .build()
34

How do you refresh an expired access token automatically?

Save to ▾
Show answer
Use an OkHttp Authenticator, which is called when the server returns 401. Inside it, synchronise so only one refresh runs at a time, call the refresh endpoint with the refresh token, save the new tokens and return the original request with the new header. If the request already carried the latest token and still failed, or refresh fails, return null and log the user out. Limit retries to avoid loops.
35

How do you test Retrofit networking code?

Save to ▾
Show answer
Use OkHttp MockWebServer to run a local server, enqueue responses with specific status codes, bodies and delays, and point Retrofit's base URL to it. Then call the API or repository and assert parsing, headers, error mapping and retry behaviour. Store sample JSON in test resources. For ViewModel tests, replace the repository with a fake instead of using MockWebServer, which keeps them fast.
36

Write a function that retries a suspend call with exponential backoff.

Save to ▾
Show answer
suspend fun <T> retryWithBackoff( times: Int = 3, initialDelay: Long = 500, factor: Double = 2.0, block: suspend () -> T ): T { var delayMs = initialDelay repeat(times - 1) { try { return block() } catch (e: IOException) { /* retry */ } delay(delayMs) delayMs = (delayMs * factor).toLong() } return block() }
37

How do you design an Android client to support API versioning and forced updates?

Save to ▾
Show answer
Send the app version in a header on every request, have the backend support older versions for a defined period, and use versioned endpoints for breaking changes. Add a remote config value for minimum supported version and use the Play In-App Updates API with immediate flow for critical updates and flexible flow otherwise. Show a clear message rather than failing silently when the app is too old.
38

Write a unit test for a ViewModel using a fake repository and runTest.

Save to ▾
Show answer
class ProductViewModelTest { @get:Rule val mainRule = MainDispatcherRule() @Test fun loadsProductsIntoState() = runTest { val fake = FakeProductRepository(listOf(Product("1", "Pen", 10.0))) val vm = ProductViewModel(fake) advanceUntilIdle() val state = vm.state.value assertFalse(state.loading) assertEquals(1, state.items.size) assertNull(state.error) } }
39

How do you find and fix memory leaks in an Android app?

Save to ▾
Show answer
Add LeakCanary to debug builds; it detects retained Activities, Fragments and ViewModels and shows the reference chain. Common leaks are static or singleton references to Context or Views, listeners not unregistered, inner classes holding Activity references, and Fragment view bindings not cleared in onDestroyView. Fix by using application context, lifecycle-aware components and weak references only where needed. Confirm with Memory Profiler heap dumps.
40

Explain the steps to publish an app on the Play Store.

Save to ▾
Show answer
Create a developer account, then an app in Play Console. Complete the store listing, content rating, data safety form, target audience, privacy policy and permissions declarations. Build a signed release AAB with a higher versionCode, upload it to internal testing first, then closed or open testing, and finally production with a staged rollout. New personal accounts must run a closed test with at least 12 testers for 14 days before production.
41

Write a Gradle configuration for release signing and minification using environment variables.

Save to ▾
Show answer
android { signingConfigs { create("release") { storeFile = file(System.getenv("KEYSTORE_PATH") ?: "release.jks") storePassword = System.getenv("KEYSTORE_PASSWORD") keyAlias = System.getenv("KEY_ALIAS") keyPassword = System.getenv("KEY_PASSWORD") } } buildTypes { release { isMinifyEnabled = true isShrinkResources = true proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro") signingConfig = signingConfigs.getByName("release") } } }
42

How do you set up CI/CD for an Android app?

Save to ▾
Show answer
On every pull request, run lint, ktlint or detekt, unit tests and a debug build in a CI service like GitHub Actions or Bitrise, with Gradle caching. On merge to main, build a signed release AAB using secrets, run instrumented tests on emulators or a device farm, and upload to the Play internal track with Gradle Play Publisher or fastlane. Promote to production manually after QA with a staged rollout.

Frequently asked questions

Why are practical questions important?

Most technical rounds include at least one live task. Practising the exact typing and reasoning makes you calm and fast in the real round.

How should I answer them?

Talk while you work: say your approach first, write the simplest correct version, then improve it and mention edge cases.