0

My app works as a client for different servers, which means that I have to deal with a changing api base url. The base url is set once at the app start by the user, and then stays the same during runtime. Normally I would use SharedPreferences to load app data, but therefore an ApplicationContext is needed.

What is the best practice for this use case?

Currently my Retrofit Service class looks like this:

import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class RetrofitService {

    private static Retrofit retrofit = new Retrofit.Builder()
            .baseUrl("https://testtapi.org/v2/")
            .addConverterFactory(GsonConverterFactory.create())
            .build();


    public static <S> S cteateService(Class<S> serviceClass) {
        return retrofit.create(serviceClass);
    }

}
  • `but therefore an ApplicationContext is needed.` what prevents you from passing in context (or any dependencies) when making your retrofit service ? – a_local_nobody Dec 24 '20 at 23:07
  • Isn't it recommended that the RetrofitService shall use a static method? If this is the case (as I think) this isn't possible – DeveloperCat1234 Dec 24 '20 at 23:12
  • `Isn't it recommended that the RetrofitService shall use a static method?` why ? – a_local_nobody Dec 24 '20 at 23:14
  • Just that you know why I don't think that this might be an good idea: I use the retrofit service in more than one activity, and passing along the application context can cause memory leaks – DeveloperCat1234 Dec 24 '20 at 23:18
  • Does this answer your question? [Static way to get 'Context' in Android?](https://stackoverflow.com/questions/2002288/static-way-to-get-context-in-android) – a_local_nobody Dec 24 '20 at 23:20
  • No, I have searched for solutions before, and have already read this 10 year old answer. This is definitely not the best way of doing it – DeveloperCat1234 Dec 24 '20 at 23:22
  • this answer contains [solutions for kotlin](https://stackoverflow.com/a/50488721/4729721), kotlin definitely isn't 10 years old. either way, you seem to know a better solution for this `This is definitely not the best way of doing it` so looking forward to seeing it ! goodluck – a_local_nobody Dec 24 '20 at 23:25
  • Sorry, if I sounded rude (was not my intention), but I looked at the top rated answer. Is there really no other way for doing this? – DeveloperCat1234 Dec 24 '20 at 23:37

0 Answers0