android-sdk
android-sdk copied to clipboard
Avoid Extending Application
I noticed the example is extending Application in DreamFactoryApp.java. As far as I know this isn't really best practice. It would be better to do the following:
Pass the context when getting an instance:
public class DreamFactoryAPI {
private static DreamFactoryAPI INSTANCE;
private final Context mContext;
private Retrofit retrofit;
private OkHttpClient httpClient;
private static Converter<ResponseBody, ErrorMessage> errorConverter;
public static String testToken;
public static Boolean runningFromTest = false;
public static DreamFactoryAPI getInstance(@NonNull Context context) { //context passed in here
synchronized(DreamFactoryAPI.class) {
if (INSTANCE == null) {
INSTANCE = new DreamFactoryAPI(context);
}
return INSTANCE;
}
}
private DreamFactoryAPI(@NonNull Context context) { //context is part of the constructor
mContext = context.getApplicationContext();
httpClient = new OkHttpClient.Builder().addInterceptor(new Interceptor() {
// existing code
}
Then in the in the activity just pass this context when making a call to the DreamFactoryAPI.
final AuthService service = DreamFactoryAPI.getInstance(this).getService(AuthService.class);
Then move some of the normal saved data like the session to a normal public interface class for shared preferences.
Thanks for the feedback. We would like to update all of the sample apps as time permits and will take your suggestion into consideration.
As a side note I didn't use my changes with unit tests yet.