我正試圖解決Retrofit 2在響應中返回null的問題。有趣的是,在模擬器中一切正常,數據被接收並顯示,但是當我構建APK時,同樣的事情會因爲NullPointerException而崩潰。我評論了發生這種情況的路線。Retrofit 2在生產中返回null
我的build.gradle依賴關係:
compile 'com.squareup.retrofit2:retrofit:2.3.0'
compile 'io.reactivex.rxjava2:rxjava:2.1.3'
compile 'io.reactivex.rxjava2:rxandroid:2.0.1'
compile 'com.jakewharton.retrofit:retrofit2-rxjava2-adapter:1.0.0'
compile 'com.squareup.retrofit2:converter-gson:2.3.0'
初始化改造:
retrofit = new Retrofit.Builder()
.baseUrl(<url>)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build();
接口:
@GET(<url>)
Flowable<DataResponse> getDataFromApi(@Query("offset") int offset, @Query("limit") int limit);
API調用:
retrofit
.getDataFromApi(0, 10)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Subscriber<DataResponse>() {
@Override
public void onSubscribe(Subscription s) {
s.request(Long.MAX_VALUE);
}
@Override
public void onNext(DataResponse dataResponse) {
// HERE I GET NULL IN PRODUCTION
}
DataResponse POJO:
public class ServicesResponse {
private List<Item> items;
public List<Item> getItems() {
return items;
}
}
ProGuard的。我嘗試了幾件事,但仍然沒有運氣。目前,它看起來像這樣:
-dontwarn retrofit2.**
-keep class javax.annotation.Nullable
-keep interface javax.annotation.Nullable
-keep class retrofit2.** { *; }
-keep class com.squareup.okhttp3.** { *; }
-keep interface com.squareup.okhttp3.** { *; }
-keepattributes Signature
-keepattributes Exceptions
-keepclasseswithmembers class * {
@retrofit2.http.* <methods>;
}
-keepclasseswithmembers interface * {
@retrofit2.http.* <methods>;
}
感謝您的幫助:)
您可以發佈NPE堆棧跟蹤嗎?您是否在使用ProGuard(當發佈版本中的行爲不同時,這通常會導致類似問題)? –
是的,忘記了ProGuard。我已更新原始帖子。當我嘗試對響應進行任何操作時,堆棧跟蹤基本上是nullpointerexception。 – Oleg
-keep public class your.package.to.models。** {*;} –