MainActivity 未实现接口 dagger.hilt.internal.GenerateComponent 或接口 dagger.hilt.internal.GenerateComponentManager

发布于 2025-01-20 20:48:45 字数 5922 浏览 0 评论 0原文

我正在学习使用JetPack Compose,并且我试图遵循一个教程,以创建使用Hilt和MVVM创建Pokedex,一切都很好,直到我尝试实现ViewModel,当我注射它并试图运行该应用程序时,我都得到了。标题错误(给定的组件持有人类com.example.pokedex.pokedex.mainactivity不实现接口匕首。hilt.Internal.generatedComponent或Interface Dagger.hilt.internal.generatect.generatecon.generatedcomponentmanager)论坛改变了注入它的方式,但它们都不对我有用。

我的代码:

pokedex应用程序:

@HiltAndroidApp
class PokedexApplication : Application() {
  override fun onCreate() {
    super.onCreate()
    Timber.plant(Timber.DebugTree())
  }
}

MainAttivity

@AndroidEntryPoint
class MainActivity : ComponentActivity() {
  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContent {
      PokedexTheme {
        val navController = rememberNavController()
        NavHost(navController = navController,
          startDestination = "pokemon_list_screen"
        ) {
          composable("pokemon_list_screen") {
            PokemonListScreen(navController = navController)
          }
          composable(
            "pokemon_detail_screen/{dominantColor}/{pokemonName}",
            arguments = listOf(
              navArgument("dominantColor") {
                type = NavType.IntType
              },
              navArgument("pokemonName") {
                type = NavType.StringType
              }
            )) {
            val dominantColor = remember {
              val color = it.arguments?.getInt("dominantColor")
              color?.let { Color(it) } ?: Color.White
            }
            val pokemonName = remember {
              it.arguments?.getString("pokemonName")

            }
          }
        }
      }
    }
  }
}

AppModule

@Module
@InstallIn(SingletonComponent::class)
object AppModule {

  @Singleton
  @Provides
  fun providePokemonRepository(
    api: PokeApi
  ) = PokemonRepository(api)

  @Singleton
  @Provides
  fun providePokeApi(): PokeApi {
    return Retrofit.Builder()
      .addConverterFactory(GsonConverterFactory.create())
      .baseUrl(BASE_URL)
      .build()
      .create(PokeApi::class.java)
  }
}

repository

@ActivityScoped
class PokemonRepository @Inject constructor (
  private val api: PokeApi
  ) {

  suspend fun getPokemonList(limit: Int, offset: Int): Resource<PokemonList> {
    val response = try {
      api.getPokemonList(limit, offset)
    } catch (e: Exception) {
      return Resource.Error(e.message.toString())
    }
    return Resource.Success(response)
  }
}

可以合并,我称为​​ViewModel

@Composable
fun PokemonList(
  navController: NavController,
  viewModel: PokemonListViewModel = hiltViewModel()
) {

  val pokemonList by remember { viewModel.pokemonList }
  val endReached by remember { viewModel.endReached }
  val loadError by remember { viewModel.loadError }
  val isLoading by remember { viewModel.isLoading }

  LazyColumn(contentPadding = PaddingValues(16.dp)) {
    val itemCount = if(pokemonList.size % 2 == 0) pokemonList.size / 2 else pokemonList.size / 2 + 1

    items(itemCount) {
      if (it >= itemCount - 1 && !endReached){
        viewModel.loadPokemonPaginated()
      }
      PokedexRow(rowIndex = it, entries = pokemonList, navController = navController)
    }
  }
}

viewModel(仅第一个代码)

@HiltViewModel
class PokemonListViewModel @Inject constructor(
  private val repository: PokemonRepository
) : ViewModel() {

  private var curPage = 0

  var pokemonList = mutableStateOf<List<PokedexListEntry>>(listOf())
  var loadError = mutableStateOf("")
  var isLoading = mutableStateOf(false)
  var endReached = mutableStateOf(false)

  init {
    loadPokemonPaginated()
  }

撰写版本: 1.1.1

kotlin版本 1.6.10

依赖项

implementation 'androidx.core:core-ktx:1.7.0'
implementation "androidx.compose.ui:ui:$compose_version"
implementation "androidx.compose.material:material:$compose_version"
implementation "androidx.compose.ui:ui-tooling-preview:$compose_version"
implementation 'androidx.lifecycle:lifecycle-runtime-ktx:2.4.1'
implementation 'androidx.activity:activity-compose:1.4.0'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
androidTestImplementation "androidx.compose.ui:ui-test-junit4:$compose_version"
debugImplementation "androidx.compose.ui:ui-tooling:$compose_version"

implementation("com.google.dagger:hilt-android:2.41")
kapt("com.google.dagger:hilt-android-compiler:2.38.1")

// Retrofit
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
implementation "com.squareup.okhttp3:okhttp:4.9.3"
implementation "com.squareup.okhttp3:logging-interceptor:4.9.0"

// Timber
implementation 'com.jakewharton.timber:timber:4.7.1'

// Coroutines
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.6.0'
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.6.0'

// Coroutine Lifecycle Scopes
implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:2.4.1"
implementation "androidx.lifecycle:lifecycle-runtime-ktx:2.4.1"

// Coil
implementation "io.coil-kt:coil:1.3.2"
implementation "com.google.accompanist:accompanist-coil:0.7.0"

//Dagger - Hilt
implementation 'com.google.dagger:hilt-android:2.41'
kapt 'com.google.dagger:hilt-compiler:2.41'
kapt "androidx.hilt:hilt-compiler:1.0.0"
implementation 'androidx.hilt:hilt-navigation-compose:1.0.0'

//Navigation
implementation "androidx.navigation:navigation-compose:2.4.2"

//Palette
implementation "androidx.palette:palette:1.0.0"

I'm learning to use Jetpack Compose and I was trying to follow a tutorial to create a Pokedex with Hilt and MVVM, everything was going well until I tried to implement the viewModel, when I injected it and tried to run the app, I got the title error ( Given component holder class com.example.pokedex.MainActivity does not implement interface dagger.hilt.internal.GeneratedComponent or interface dagger.hilt.internal.GeneratedComponentManager ), I already tried several solutions from the forum changing the way of injecting it but none of them has worked for me.

My code:

Pokedex Application:

@HiltAndroidApp
class PokedexApplication : Application() {
  override fun onCreate() {
    super.onCreate()
    Timber.plant(Timber.DebugTree())
  }
}

MainActivity

@AndroidEntryPoint
class MainActivity : ComponentActivity() {
  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContent {
      PokedexTheme {
        val navController = rememberNavController()
        NavHost(navController = navController,
          startDestination = "pokemon_list_screen"
        ) {
          composable("pokemon_list_screen") {
            PokemonListScreen(navController = navController)
          }
          composable(
            "pokemon_detail_screen/{dominantColor}/{pokemonName}",
            arguments = listOf(
              navArgument("dominantColor") {
                type = NavType.IntType
              },
              navArgument("pokemonName") {
                type = NavType.StringType
              }
            )) {
            val dominantColor = remember {
              val color = it.arguments?.getInt("dominantColor")
              color?.let { Color(it) } ?: Color.White
            }
            val pokemonName = remember {
              it.arguments?.getString("pokemonName")

            }
          }
        }
      }
    }
  }
}

AppModule

@Module
@InstallIn(SingletonComponent::class)
object AppModule {

  @Singleton
  @Provides
  fun providePokemonRepository(
    api: PokeApi
  ) = PokemonRepository(api)

  @Singleton
  @Provides
  fun providePokeApi(): PokeApi {
    return Retrofit.Builder()
      .addConverterFactory(GsonConverterFactory.create())
      .baseUrl(BASE_URL)
      .build()
      .create(PokeApi::class.java)
  }
}

Repository

@ActivityScoped
class PokemonRepository @Inject constructor (
  private val api: PokeApi
  ) {

  suspend fun getPokemonList(limit: Int, offset: Int): Resource<PokemonList> {
    val response = try {
      api.getPokemonList(limit, offset)
    } catch (e: Exception) {
      return Resource.Error(e.message.toString())
    }
    return Resource.Success(response)
  }
}

Composable where I call the ViewModel

@Composable
fun PokemonList(
  navController: NavController,
  viewModel: PokemonListViewModel = hiltViewModel()
) {

  val pokemonList by remember { viewModel.pokemonList }
  val endReached by remember { viewModel.endReached }
  val loadError by remember { viewModel.loadError }
  val isLoading by remember { viewModel.isLoading }

  LazyColumn(contentPadding = PaddingValues(16.dp)) {
    val itemCount = if(pokemonList.size % 2 == 0) pokemonList.size / 2 else pokemonList.size / 2 + 1

    items(itemCount) {
      if (it >= itemCount - 1 && !endReached){
        viewModel.loadPokemonPaginated()
      }
      PokedexRow(rowIndex = it, entries = pokemonList, navController = navController)
    }
  }
}

ViewModel (Just first code)

@HiltViewModel
class PokemonListViewModel @Inject constructor(
  private val repository: PokemonRepository
) : ViewModel() {

  private var curPage = 0

  var pokemonList = mutableStateOf<List<PokedexListEntry>>(listOf())
  var loadError = mutableStateOf("")
  var isLoading = mutableStateOf(false)
  var endReached = mutableStateOf(false)

  init {
    loadPokemonPaginated()
  }

Compose version: 1.1.1

Kotlin version 1.6.10

Dependencies

implementation 'androidx.core:core-ktx:1.7.0'
implementation "androidx.compose.ui:ui:$compose_version"
implementation "androidx.compose.material:material:$compose_version"
implementation "androidx.compose.ui:ui-tooling-preview:$compose_version"
implementation 'androidx.lifecycle:lifecycle-runtime-ktx:2.4.1'
implementation 'androidx.activity:activity-compose:1.4.0'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
androidTestImplementation "androidx.compose.ui:ui-test-junit4:$compose_version"
debugImplementation "androidx.compose.ui:ui-tooling:$compose_version"

implementation("com.google.dagger:hilt-android:2.41")
kapt("com.google.dagger:hilt-android-compiler:2.38.1")

// Retrofit
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
implementation "com.squareup.okhttp3:okhttp:4.9.3"
implementation "com.squareup.okhttp3:logging-interceptor:4.9.0"

// Timber
implementation 'com.jakewharton.timber:timber:4.7.1'

// Coroutines
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.6.0'
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.6.0'

// Coroutine Lifecycle Scopes
implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:2.4.1"
implementation "androidx.lifecycle:lifecycle-runtime-ktx:2.4.1"

// Coil
implementation "io.coil-kt:coil:1.3.2"
implementation "com.google.accompanist:accompanist-coil:0.7.0"

//Dagger - Hilt
implementation 'com.google.dagger:hilt-android:2.41'
kapt 'com.google.dagger:hilt-compiler:2.41'
kapt "androidx.hilt:hilt-compiler:1.0.0"
implementation 'androidx.hilt:hilt-navigation-compose:1.0.0'

//Navigation
implementation "androidx.navigation:navigation-compose:2.4.2"

//Palette
implementation "androidx.palette:palette:1.0.0"

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

深居我梦 2025-01-27 20:48:45

对于所有将来遇到相同问题并且即使调整依赖项也没有帮助的人:检查您是否使用@AndroidEntryPoint注释您的活动!还要检查是否缺少 @H​​iltViewModel 注释。这对我有用

For all those who have the same problem in the future and where even adjusting the dependencies did not help: Check whether you have annotated your activity with @AndroidEntryPoint! Also check for missing @HiltViewModel annotations. That did the trick for me

浊酒尽余欢 2025-01-27 20:48:45

如果这可以帮助的话,我也遇到了同样的问题。我设法通过将其添加到我的应用程序模块中的 build.gradle 中(

id("kotlin-kapt")
id("dagger.hilt.android.plugin")

在插件部分的根 build.gradle 中)

id("com.google.dagger.hilt.android") version "2.44" apply false

以及我的应用程序 build.gradle 中的所有这些依赖项来

implementation("com.google.dagger:hilt-android:2.44")
kapt("com.google.dagger:hilt-android-compiler:2.44")
implementation("androidx.hilt:hilt-work:1.0.0")
kapt("androidx.hilt:hilt-compiler:1.0.0")
implementation("androidx.work:work-runtime-ktx:2.8.1")
implementation("androidx.hilt:hilt-navigation-compose:1.0.0")

解决这个问题,这是我第一次在 Hilt 中遇到此问题。我认为这是因为我没有像以前那样完全安装 Hilt,在 root build.gradle 和 app build.gradle 中安装所有这些依赖项

If that could help, I had the same issue. I manage to solve it by adding this to my build.gradle in my app module

id("kotlin-kapt")
id("dagger.hilt.android.plugin")

this in my root build.gradle in the plugins sections

id("com.google.dagger.hilt.android") version "2.44" apply false

and all theses dependencies in my app build.gradle

implementation("com.google.dagger:hilt-android:2.44")
kapt("com.google.dagger:hilt-android-compiler:2.44")
implementation("androidx.hilt:hilt-work:1.0.0")
kapt("androidx.hilt:hilt-compiler:1.0.0")
implementation("androidx.work:work-runtime-ktx:2.8.1")
implementation("androidx.hilt:hilt-navigation-compose:1.0.0")

That's the first time I encounter this issue with Hilt. I think it's because I didn't fully install Hilt as I used to with all theses dependencies in root build.gradle and app build.gradle

ま昔日黯然 2025-01-27 20:48:45
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文