使用Gradle构建配置字段不工作



我试图使用API_URL从我的构建。gradle将其与改造一起使用,但我得到了"未解决的参考"。错误在我的RetrofitServices文件,所以我如何修复它?

  • Build.gradle:
flavorDimensions "environment"
productFlavors{
create("develop"){
dimension = "environment"
applicationIdSuffix = ".develop"
versionNameSuffix = "-develop"
buildConfigField "String", "API_URL", ""https://rickandmortyapi.com/""
}
create("production"){
dimension = "environment"
applicationIdSuffix = ".production"
versionNameSuffix = "-production"
buildConfigField "String", "API_URL", ""https://rickandmortyapi.com/""
}
}
  • 改造服务:
object RetrofitServices {
val instance: Retrofit
get()  {
val httpClient = OkHttpClient.Builder()
.addInterceptor(HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))
.build()
return Retrofit.Builder()
.baseUrl(BuildConfig.API_URL)
.addConverterFactory(GsonConverterFactory.create())
.client(httpClient)
.build()
}
}

当你将buildConfigField添加到Gradle设置中时,它告诉构建工具将所需的字段添加到BuildConfig。然而,添加字段不会发生在你输入build.gradle的权利。它将在应用程序的下一个构建中发生。然后,新字段应该出现。

所以,在尝试引用新字段之前构建应用程序,然后新字段应该在那里等你。

如果字段没有出现:

  • 确保您正在导入正确的BuildConfig

  • 确保您的build.gradle设置为每个可能的构建变体定义了buildConfigField

最新更新