Search code examples
javaandroidandroid-multidex

How to solve Android MultiDex Apllication Instance Null Pointer Exception?


I want to do a core api service integration in my Android project. My core service class is as follows:

public class TestApplication extends MultiDexApplication {
    private static final String LOG_TAG_NETWORK = "GNetwork";
    public static JacksonConverterFactory factory;
    private static TestApplication instance;
    private OkHttpClient.Builder okHttpBuilder;
    private TestService testtService;
    private Location lastKnownLocation;

public static TestApplication getInstance() {
    return instance;
}

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

    Pref.init(this);

    okHttpBuilder = new OkHttpClient.Builder();
    okHttpBuilder.connectTimeout(UrlConstants.CONNECT_TIMEOUT_IN_SECONDS, TimeUnit.SECONDS)
            .readTimeout(UrlConstants.READ_TIMEOUT_IN_SECONDS, TimeUnit.SECONDS)
            .writeTimeout(UrlConstants.WRITE_TIMEOUT_IN_SECONDS, TimeUnit.SECONDS);
    if (BuildConfig.LOG_ENABLED) {
        HttpLoggingInterceptor httpLoggingInterceptor =
                new HttpLoggingInterceptor(message -> Log.d(LOG_TAG_NETWORK, message));
        httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

        okHttpBuilder.addInterceptor(httpLoggingInterceptor);
    }
    factory = getJacksonConverterFactory();
}

@NonNull
private JacksonConverterFactory getJacksonConverterFactory() {
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    return JacksonConverterFactory.create(objectMapper);
}

public void setupRetrofit() {

    String BASE_URL = "http://xxxxx";

    Retrofit retrofit = new Retrofit.Builder().baseUrl(BASE_URL).client(okHttpBuilder.build())
            .addConverterFactory(factory).build();

    testService = retrofit.create(TestService.class);
}

public TestService getTestService() {
    return testService;
    }
}

Then I create an instance from this core class. But here my constant getIntance value returns null.

TestApplication.getInstance().setupRetrofit();

I can't understand that. GetInstance method always return null;

In my app build.gradle file is multiDexEnabled true.

How to solve this situation?


Solution

  • never use instance of application like this. for get application instance you need activity and in your activity you can use

        static TestApplication getInstance(Activity activity) {
            if (instance == null)
                instance = ((TestApplication) activity.getApplication());
            return instance;
        }
    

    this will solve your issues but the way you implement retrofit and using it is not best practices. You can find better way that doesn't need activity.