Bird
Raised Fist0
Android Kotlinmobile~20 mins

Dependency injection with Hilt in depth in Android Kotlin - Mini App: Build & Ship

Choose your learning style10 modes available
Build: User Profile Screen
This screen shows a user's profile information fetched from a repository. It uses Hilt for dependency injection to provide the repository to the ViewModel.
Target UI
-------------------------
|      User Profile      |
-------------------------
| Name: Loading...       |
| Email: Loading...      |
|                       |
| [Refresh]             |
-------------------------
Use Hilt to inject UserRepository into UserViewModel
UserRepository provides user data (name and email)
UserViewModel fetches user data from UserRepository
UserProfileScreen observes ViewModel and displays user info
Add a Refresh button to reload user data
Show 'Loading...' text while data is loading
Starter Code
Android Kotlin
package com.example.hiltdemo

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Button
import androidx.compose.material3.Text
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import dagger.hilt.android.AndroidEntryPoint
import javax.inject.Inject
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch

// TODO: Define User data class
// TODO: Define UserRepository interface and implementation
// TODO: Setup Hilt module to provide UserRepository
// TODO: Create UserViewModel with injected UserRepository
// TODO: Build UserProfileScreen composable to display user info

@AndroidEntryPoint
class MainActivity : ComponentActivity() {
  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContent {
      MaterialTheme {
        Surface(modifier = Modifier.padding(16.dp)) {
          UserProfileScreen()
        }
      }
    }
  }
}

@Composable
fun UserProfileScreen() {
  // TODO: Get UserViewModel instance
  // TODO: Observe user data state
  // TODO: Display user name and email or Loading...
  // TODO: Add Refresh button to reload data
}
Task 1
Task 2
Task 3
Task 4
Task 5
Task 6
Task 7
Task 8
Task 9
Solution
Android Kotlin
package com.example.hiltdemo

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Button
import androidx.compose.material3.Text
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import dagger.hilt.android.AndroidEntryPoint
import dagger.hilt.android.lifecycle.HiltViewModel
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import javax.inject.Inject
import javax.inject.Singleton
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch
import androidx.hilt.navigation.compose.hiltViewModel

// Data class representing a user
data class User(val name: String, val email: String)

// Repository interface
interface UserRepository {
  suspend fun getUser(): User
}

// Repository implementation
class UserRepositoryImpl @Inject constructor() : UserRepository {
  override suspend fun getUser(): User {
    // Simulate network or database delay
    kotlinx.coroutines.delay(1000)
    return User(name = "Alice Johnson", email = "alice@example.com")
  }
}

// Hilt module to provide UserRepository
@Module
@InstallIn(SingletonComponent::class)
object UserRepositoryModule {
  @Provides
  @Singleton
  fun provideUserRepository(): UserRepository = UserRepositoryImpl()
}

// ViewModel with injected UserRepository
@HiltViewModel
class UserViewModel @Inject constructor(
  private val userRepository: UserRepository
) : ViewModel() {
  private val _user = MutableStateFlow<User?>(null)
  val user: StateFlow<User?> = _user

  init {
    loadUser()
  }

  fun loadUser() {
    viewModelScope.launch {
      _user.value = null // Show loading
      val fetchedUser = userRepository.getUser()
      _user.value = fetchedUser
    }
  }
}

@AndroidEntryPoint
class MainActivity : ComponentActivity() {
  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContent {
      MaterialTheme {
        Surface(modifier = Modifier.padding(16.dp)) {
          UserProfileScreen()
        }
      }
    }
  }
}

@Composable
fun UserProfileScreen(viewModel: UserViewModel = hiltViewModel()) {
  val userState by viewModel.user.collectAsState()

  Column {
    if (userState == null) {
      Text(text = "Name: Loading...")
      Text(text = "Email: Loading...")
    } else {
      Text(text = "Name: ${userState!!.name}")
      Text(text = "Email: ${userState!!.email}")
    }
    Button(onClick = { viewModel.loadUser() }, modifier = Modifier.padding(top = 16.dp)) {
      Text("Refresh")
    }
  }
}

This solution uses Hilt to inject the UserRepository into the UserViewModel. The UserRepositoryImpl simulates fetching user data with a delay. The UserViewModel exposes a StateFlow of User? to represent loading and loaded states.

The UserProfileScreen composable gets the ViewModel instance via hiltViewModel(), observes the user state, and shows "Loading..." text while data is null. When data is loaded, it displays the user's name and email. The Refresh button calls loadUser() to reload data.

This setup demonstrates dependency injection with Hilt, ViewModel state management, and Compose UI updates reacting to state changes.

Final Result
Completed Screen
-------------------------
|      User Profile      |
-------------------------
| Name: Alice Johnson    |
| Email: alice@example.com|
|                       |
| [Refresh]             |
-------------------------
When the screen loads, it shows 'Loading...' for name and email for about 1 second.
Then it displays the user's name and email.
Tapping the Refresh button reloads the user data and shows 'Loading...' again briefly.
Stretch Goal
Add a loading spinner while user data is loading instead of just text.
💡 Hint
Use Compose's CircularProgressIndicator composable and show it conditionally when user data is null.

Practice

(1/5)
1. What is the primary purpose of using @Module and @Provides annotations in Hilt?
easy
A. To tell Hilt how to create and supply dependencies
B. To mark an Android Activity for injection
C. To automatically generate UI components
D. To define navigation between screens

Solution

  1. Step 1: Understand the role of @Module

    @Module is used to group methods that provide dependencies to Hilt.
  2. Step 2: Understand the role of @Provides

    @Provides annotates methods inside a module to tell Hilt how to create specific dependencies.
  3. Final Answer:

    To tell Hilt how to create and supply dependencies -> Option A
  4. Quick Check:

    @Module + @Provides = supply dependencies [OK]
Hint: Remember: @Module groups, @Provides creates dependencies [OK]
Common Mistakes:
  • Confusing @Module with @AndroidEntryPoint
  • Thinking @Provides creates UI elements
  • Assuming @Module is for navigation
2. Which of the following is the correct way to inject a dependency into an Android Activity using Hilt?
easy
A. Annotate the Activity with @AndroidEntryPoint and use @Inject on the field
B. Use @Module on the Activity class
C. Call Hilt.inject(this) inside onCreate()
D. Add @Provides on the Activity constructor

Solution

  1. Step 1: Identify how to enable injection in Activity

    Hilt requires the Activity to be annotated with @AndroidEntryPoint to generate necessary code.
  2. Step 2: Inject dependencies with @Inject

    Fields or constructor parameters annotated with @Inject receive dependencies automatically.
  3. Final Answer:

    Annotate the Activity with @AndroidEntryPoint and use @Inject on the field -> Option A
  4. Quick Check:

    @AndroidEntryPoint + @Inject field = inject Activity dependency [OK]
Hint: Use @AndroidEntryPoint on Activity, then @Inject fields [OK]
Common Mistakes:
  • Trying to use @Module on Activity
  • Calling non-existent Hilt.inject() method
  • Adding @Provides on constructors
3. Given the following code snippet, what will be the output when MyViewModel is injected?
class MyRepository @Inject constructor() {
    fun getData() = "Data from repository"
}

@HiltViewModel
class MyViewModel @Inject constructor(private val repo: MyRepository) : ViewModel() {
    fun fetch() = repo.getData()
}
medium
A. "fetch() method not found"
B. NullPointerException at runtime
C. Compilation error due to missing @Provides
D. "Data from repository"

Solution

  1. Step 1: Understand constructor injection in MyRepository

    MyRepository has an @Inject constructor, so Hilt can create it automatically.
  2. Step 2: MyViewModel receives MyRepository via constructor injection

    Hilt injects MyRepository instance into MyViewModel, so calling fetch() returns repo.getData() string.
  3. Final Answer:

    "Data from repository" -> Option D
  4. Quick Check:

    Constructor injection returns data string [OK]
Hint: If constructor has @Inject, Hilt creates instance automatically [OK]
Common Mistakes:
  • Assuming @Provides is always needed
  • Expecting runtime null errors with constructor injection
  • Confusing method names in ViewModel
4. Identify the error in this Hilt module code:
@Module
@InstallIn(SingletonComponent::class)
object NetworkModule {
    @Provides
    fun provideHttpClient(): OkHttpClient {
        return OkHttpClient()
    }

    @Provides
    fun provideRetrofit(client: OkHttpClient): Retrofit {
        return Retrofit.Builder()
            .client(client)
            .baseUrl("https://api.example.com")
            .build()
    }
}
medium
A. Missing @Singleton annotation on provider methods
B. Retrofit.Builder() requires a converter factory
C. OkHttpClient cannot be provided without parameters
D. NetworkModule should be a class, not an object

Solution

  1. Step 1: Review Retrofit.Builder usage

    Retrofit requires a converter factory (like GsonConverterFactory) to parse responses; missing here causes runtime error.
  2. Step 2: Check other options for correctness

    @Singleton is optional but recommended; object is valid for modules; OkHttpClient can be created without parameters.
  3. Final Answer:

    Retrofit.Builder() requires a converter factory -> Option B
  4. Quick Check:

    Retrofit needs converter factory to build properly [OK]
Hint: Retrofit always needs a converter factory to avoid errors [OK]
Common Mistakes:
  • Thinking @Singleton is mandatory for all providers
  • Confusing object vs class for modules
  • Assuming OkHttpClient needs parameters
5. You want to inject two different implementations of an interface Logger using Hilt. How can you distinguish them during injection?
hard
A. Use @Singleton on one implementation and omit on the other
B. Create two separate modules with the same provider method name
C. Use @Named qualifiers with different names on provider methods and injection points
D. Inject both implementations into a list automatically

Solution

  1. Step 1: Understand multiple implementations injection

    When multiple bindings exist for the same type, Hilt requires qualifiers to distinguish them.
  2. Step 2: Use @Named qualifiers

    Annotate provider methods and injection points with @Named("name") to specify which implementation to inject.
  3. Final Answer:

    Use @Named qualifiers with different names on provider methods and injection points -> Option C
  4. Quick Check:

    Multiple implementations need @Named qualifiers [OK]
Hint: Use @Named("tag") to differentiate implementations [OK]
Common Mistakes:
  • Assuming module separation alone distinguishes implementations
  • Using @Singleton to differentiate implementations
  • Expecting automatic list injection without setup
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard