1

I need to set retrofit base URL from Strings.xml file. However, the service generator can't access the Context class in Android. Can anyone give any advice?

Here's the snapshot of my code

private static Retrofit.Builder builder =
        new Retrofit.Builder()
                .baseUrl(API_BASE_URL)
                .baseUrl("http://localhost/")
                .addConverterFactory(GsonConverterFactory.create(new GsonBuilder().setLenient
                        ().create()));
Eldwin Eldwin
  • 1,084
  • 2
  • 11
  • 29

2 Answers2

0

Unfortunately, the only way you can access any of the string resources is with a Context (i.e. an Activity or Service). What I've usually done in this case, is to simply require the caller to pass in the context.

You can use only system resources only without Context:

Resources.getSystem().getString(android.R.string.somecommonstuff)

try below solutions

  1. Create a subclass of Application, for instance public class App extends Application {
  2. Set the android:name attribute of your <application> tag in the AndroidManifest.xml to point to your new class, e.g. android:name=".App"
  3. In the onCreate() method of your app instance, save your context (e.g. this) to a static field named mContext and create a static method that returns this field, e.g. getContext():

This is how it should look:

public class App extends Application{

    private static Context mContext;

    @Override
    public void onCreate() {
        super.onCreate();
        mContext = this;
    }

    public static Context getContext(){
        return mContext;
    }
}

Now you can use: App.getContext() whenever you want to get a context, and then getResources() (or App.getContext().getResources()).

private static Retrofit.Builder builder =
        new Retrofit.Builder()
                .baseUrl(API_BASE_URL)
                .baseUrl(App.getContext().getResources().getString(R.string.YOUR_STRING);)
                .addConverterFactory(GsonConverterFactory.create(new GsonBuilder().setLenient
                        ().create()));
Kanaiya Katarmal
  • 5,974
  • 4
  • 30
  • 56
0

Its always better to add the Retrofit dependency in class which extends Application.

And in that case you can easily instantiate your retrofit object by setting the base url using the getString() method and storing the url in strings.xml file.

Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(getString(R.string.server_url))
                .addConverterFactory(ScalarsConverterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .client(httpClient)
                .build();
Mochamad Taufik Hidayat
  • 1,264
  • 3
  • 21
  • 32
Raj Saraogi
  • 1,780
  • 1
  • 13
  • 21