Retrofit 2在生产中返回null

时间:2017-10-21 10:06:18

标签: android retrofit rx-java2

我试图解决Retrofit 2在响应中返回null的问题。有趣的是,在模拟器中一切正常,数据被接收和显示,但是当我构建APK时,同样的事情与NullPointerException崩溃。我已经评论了发生这种情况的路线。

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

感谢您的帮助:)

2 个答案:

答案 0 :(得分:2)

我总是保留Retrofit使用的模型类来进行混淆。否则AFAIK Gson无法序列化/反序列化Model:

-keep public class your.package.to.models.** {*;} 

答案 1 :(得分:0)

在POJO中使用@SerializedName(“ items”),不要对模型禁用ProGuard。

public class ServicesResponse {
  @SerializedName("items")
  private List<Item> items;

  public List<Item> getItems() {
    return items;
  }
}