android-sdk icon indicating copy to clipboard operation
android-sdk copied to clipboard

Avoid Extending Application

Open zerox1212 opened this issue 8 years ago • 2 comments

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.

zerox1212 avatar Oct 16 '17 22:10 zerox1212

Thanks for the feedback. We would like to update all of the sample apps as time permits and will take your suggestion into consideration.

todda48 avatar Oct 17 '17 20:10 todda48

As a side note I didn't use my changes with unit tests yet.

zerox1212 avatar Oct 19 '17 04:10 zerox1212