gpt4 book ai didi

java - 如何解决Android MultiDex应用实例空指针异常?

转载 作者:行者123 更新时间:2023-12-01 18:25:29 25 4
gpt4 key购买 nike

我想在我的 Android 项目中进行核心 API 服务集成。我的核心服务类如下:

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;
}
}

然后我从这个核心类创建一个实例。但这里我的常量 getIntance 值返回 null。

TestApplication.getInstance().setupRetrofit();

我无法理解这一点。 GetInstance 方法始终返回 null

在我的应用中 build.gradle 文件是 multiDexEnabled true

这种情况如何解决?

最佳答案

永远不要使用这样的应用程序实例。为了获取应用程序实例,您需要 Activity ,并且在您的 Activity 中您可以使用

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

这将解决您的问题,但您实现改造和使用它的方式不是最佳实践。您可以找到不需要 Activity 的更好方法。

关于java - 如何解决Android MultiDex应用实例空指针异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60238021/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com