dreamfactorysoftware / android-sdk

An address book app for Android showing user registration, user login, and CRUD.
46 stars 61 forks source link

Avoid Extending Application #14

Open zerox1212 opened 7 years ago

zerox1212 commented 7 years ago

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.

todda48 commented 7 years ago

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

zerox1212 commented 7 years ago

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