【问题标题】:Retrofit and Rxjava "Unable to create converter for java.util.List<Model>"改造和 Rxjava“无法为 java.util.List<Model> 创建转换器”
【发布时间】:2018-10-19 12:51:34
【问题描述】:

在我的 android 应用程序中使用带有 Retrofit 的 Rxjava 时遇到问题,在代码实现中一切似乎都很好,但是每当我导航到带有以下错误消息的活动/片段时应用程序就会崩溃。

//Error message
java.lang.IllegalArgumentException: Unable to create converter for java.util.List<com.thebestprice.bestprice.model.SearchRequestModel>
        for method DataEndpointService.getStarredRepositories

//端点声明

@GET("users/{user}/starred")
    Observable<List<SearchRequestModel>> getStarredRepositories(@Path("user") String username);

//客户端类

public class DataClient {

private static final String PROJECT_BASE_URL = "https://api.github.com/";
    private static DataClient instance;
    private DataEndpointService queryResultService;


    private DataClient(){
        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build();

        final Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create();

        final Retrofit retrofit = new Retrofit.Builder().baseUrl(PROJECT_BASE_URL)
                .client(client)
                .addConverterFactory(GsonConverterFactory.create(gson))
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();

        queryResultService = retrofit.create(DataEndpointService.class);
    }

    public static DataClient getInstance(){
        if (instance == null){
            instance = new DataClient();
        }
        return instance;
    }

public io.reactivex.Observable<List<SearchRequestModel>> queryForUserRepo(@NonNull String searchRequestModel){
        return queryResultService.getStarredRepositories(searchRequestModel);
    }
}

//片段显示列表

private void queryResultForSearchData(String userName){

        disposable = DataClient.getInstance().
                queryForUserRepo(userName).
                subscribeOn(Schedulers.io()).
                observeOn(AndroidSchedulers.mainThread()).
                subscribe(new Consumer<List<SearchRequestModel>>() {
                              @Override
                              public void accept(List<SearchRequestModel> searchRequestModels) throws Exception {
                                  mShimmerFrameLayout.stopShimmerAnimation();
                                  rvAllSearch.setAdapter(new ResultAdapter(getActivity(), searchRequestModels));
                              }
                          },
                        new Consumer<Throwable>() {
                            @Override
                            public void accept(Throwable throwable) throws Exception {

                            }`enter code here`
                        });
    }

//rxjava 的 gradle 依赖项并使用 compileSdk27 进行改造

//For using RxJava
    implementation 'io.reactivex.rxjava2:rxandroid:2.0.2'
    implementation 'io.reactivex.rxjava2:rxjava:2.1.12'

    //logging interceptor
    implementation 'com.squareup.okhttp3:logging-interceptor:3.9.1'

    //For Using retrofit to do network request
    implementation 'com.squareup.retrofit2:retrofit:2.4.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.4.0'
    implementation 'com.squareup.retrofit2:adapter-rxjava2:2.4.0'

不知道我做错了什么,搜索了类似的问题,但对我自己的情况似乎没有帮助

【问题讨论】:

    标签: java android android-studio retrofit2 rx-android


    【解决方案1】:

    当您添加 GsonConverterFactory。 查看你使用的 Bean (SearchRequestModel) 变量或 @SerializedName(alternate) 注解没有相同的变量名。

    对我有用

    【讨论】:

      【解决方案2】:

      使用RxJava的要点是避免循环和列表,调用订阅和映射函数,导致Observables管理所有项目。所以你不需要返回List

      只是使用Github API with Rx 的示例之一。

      public interface GithubService {
          String SERVICE_ENDPOINT = "https://api.github.com";
      
          @GET("/users/{login}")
          Observable<Github> getUserRx(@Path("login") String login);
      
          @GET("/users/{login}")
          Github getUser(@Path("login") String login);
      }
      

      .

      public class ServiceFactory {
      
          /**
           * Creates a retrofit service from an arbitrary class (clazz)
           * @param clazz Java interface of the retrofit service
           * @param endPoint REST endpoint url
           * @return retrofit service with defined endpoint
           */
          public static <T> T createRetrofitService(final Class<T> tClass, final String endPoint) {
              final RestAdapter restAdapter = new RestAdapter.Builder()
                      .setEndpoint(endPoint)
                      .build();
              T service = restAdapter.create(tClass);
      
              return service;
          }
      }
      

      .

              // .....
              service = ServiceFactory.createRetrofitService(
                      GithubService.class, GithubService.SERVICE_ENDPOINT);
      
      service.getUserRx(login)
                          .subscribeOn(Schedulers.newThread())
                          .observeOn(AndroidSchedulers.mainThread())
                          .cache()
                          .subscribe(new Subscriber<Github>() {
                              @Override
                              public final void onCompleted() {
                              }
      
                              @Override
                              public final void onError(Throwable e) {
                                  Log.e(LOG, " ErrorRx Default Github" + e.getMessage());
                              }
      
                              @Override
                              public final void onNext(Github response) {
                                  mCardAdapter.addData(response);
                              }
                          });
      
      // .....
      

      【讨论】:

      • 您能否为上述示例提供 RecyclerAdapter 和 ViewHolder 实现?
      • 你的时间很宝贵,当你尝试使用上面提到的方法时,我在 RecyclerviewAdapter 和 viewholder 上遇到了一个错误,请更多地说明这一点
      • @sodiqOladeni 我附上了所有来源的 github 链接。有非常简单的使用 Github API 和 Rx 的例子。
      猜你喜欢
      • 2016-03-22
      • 2016-06-23
      • 2021-05-13
      • 1970-01-01
      • 1970-01-01
      • 2021-06-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多