Home > Mobile >  can't access sharedpreferences "An annotation argument must be a compile-time constant&quo
can't access sharedpreferences "An annotation argument must be a compile-time constant&quo

Time:04-17

i want to put the token from sharedpreferences and put it in the headers. but i can't access it. it says "An annotation argument must be a compile-time constant".

here is my code:

interface ApiService {
  val session: Session

  @GET("stories")
  @Headers("Authorization : Bearer ${session.getToken()!!}")
  fun getAllStories() : Call<ListStory>
}

here is my sharedpreferences class:

class Session(context: Context) {
companion object {
    private const val PREFS_NAME = "user_pref"
    const val TOKEN = "token"
    const val LOGGED_IN = "logged_in"
}

private var preferences: SharedPreferences = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)

fun saveToken(token: String){
    val editor = preferences.edit()
    editor.putString(TOKEN, token)
    editor.apply()
}

fun getToken(): String? {
    return preferences.getString(TOKEN, "")
}

}

CodePudding user response:

Only constants can be passed inside an annotation, so you cannot add any headers with a method call inside an annotation.

But you can dynamically add headers to your request or you can add headers to all of your retrofit request itself.

Dynamically adding headers

@GET("stories")
fun getAllStories(@Header("Authorization") autorizationToken: String) : Call<ListStory>

Now while calling getAllStories, just pass authorization token

api.getAllStories("Bearer ${session.getToken()!!}")

Static headers

or you can add headers, for all of your requests

val request = Request.Builder()
                .url(url)
                .addHeader("Authorization", "Bearer ${session.getToken()!!}")
                .build()
  • Related