我试图使用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