How to get res Strings.xml from a retrofit interface class?

Viewed 163

I have a string in res/strings.xml

<string name="clientId">dfgljkwm51</string>

I want to use the string inside my retrofit interface class:


public class RetrofitInterfaces {
        public interface GetAlbum{
             @Headers("Authorization: Client-ID " + clientId) //Want to use the String valye here.
             @GET
             Call<Feed> listRepos(@Url String url);
        }
}

This is how im using the retrofit call:

 private void makeNetworkCall(String url) {
        RetrofitInterfaces.GetAlbum service = RetrofitClientInstance.getRetrofitInstance()
                .create(RetrofitInterfaces.GetAlbum.class);
        Call<Feed> call = service.listRepos(url);
        call.enqueue(new Callback<Feed>() {
            . . . 
}

How do I pass this value into my Retrofit interfaces class so that I can use the value in the headers?

3 Answers

strings.xml is there for localization, you probably shouldn't be using it to store api key values.

You can instead use BuildConfig fields :

buildConfigField "String", "API_KEY", '"key"'

Which you can then access anywhere with BuildConfig.API_KEY

Complete example, this is in your Build.Gradle(:app)

defaultConfig {
        applicationId "your app"
        minSdkVersion 21
        targetSdkVersion 30
        versionCode buildVersionCode
        versionName buildVersionName
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"

        buildConfigField "String", "API_KEY", '"api key here"'
    }

BuildConfig fields have the additional benefit of providing a way of keeping your source code safe when uploading it as open source, by allowing you to read your key into a build config variable from an external file

Make a class for constant values

public class Constants {

public static final String key = "as23rsffwr2";

}

Access like this

Constants.key

I would just create a constant as Haseeb Mirza mentioned. A build config field can be useful when you need to have a different client id in a different environment.

Related