Reputation: 279
I've refactored some parts of my code which is written in Kotlin and tend to put url's in strings.xml, but when I want to point to the string in strings.xml file in annotation part of the Retrofit, I get the following error.
An annotation argument must be a compile-time constant
Here is my code:
interface SampleApiService {
@GET(Resources.getSystem().getString(R.string.sample_url))
fun getSamples(){
}
}
Could anyone please tell me what is wrong?
Found the answer in the following post.
Upvotes: 0
Views: 1532
Reputation: 76669
Based upon the example provided - one could as well just use a static URL. It would need to be annotated alike this, in order not to use any run-time values and be able to change it at run-time:
@GET("{path}")
fun getSamples(@Path("path") path: String) {}
Then one can load whatever String path
from string resources, at run-time. When the base URL shall be changed, one may need to reconfigure the client. That is because this interface
definition is being used by the annotation processor to generate the abstraction layer from it - at compile time already, not at run-time... when taking the complaint literal, it would have to look alike this:
@GET(Constants.SOME_PATH)
fun getSamples() {}
but there is little advance over just hard-coding that String
, because it cannot be changed later.
Upvotes: 0
Reputation: 279
Problem solved, Tnx to Retrofit 2 - Dynamic URL
I had to use another annotation mark of retrofit.
New: @Url parameter annotation allows passing a complete URL for an endpoint.
Here is the result:
interface SampleApiService {
@GET
fun getSamples(
@Url url: String =
Resources.getSystem().getString(R.string.sample_url)
)
: Deferred<ArrayList<Sample>>
}
Upvotes: 0
Reputation: 1105
As documentation states it compiles your application resources at build time. and Annotation processing takes place at compile time. So you see you cannot pass resources string to a annotation
The Android SDK tools compile your application's resources into the application binary at build time.
instead create static string variable and pass it in annotation
Upvotes: 1