带有retrofit2的java.lang.IllegalArgumentException

时间:2017-11-08 14:17:21

标签: android retrofit2

我需要通过改造来实现简单的例子。我用下一个

gradle dependensy:

public interface TestService {
        @GET("test")
        Test getUser();
    }

接口:

button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Retrofit retrofit = new Retrofit.Builder()
                        .baseUrl("http://localhost:8080")
                        .addConverterFactory(GsonConverterFactory.create())
                        .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                        .build();

                TestService service = retrofit.create(TestService.class);
                Test test = service.getUser();
                Log.d("button_click", "test: "+ test);
            }
        });
主要活动中的

java.lang.IllegalArgumentException: Could not locate call adapter for class mydomain.nfpclient.models.Test.
  Tried:
   * retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
   * retrofit2.ExecutorCallAdapterFactory

错误

.getElementsByTagName()

1 个答案:

答案 0 :(得分:3)

您必须更改界面:

public interface TestService {
    @GET("test")
    Call<Test> getUser(); //Call<Test> instead of just Test
}

然后,像这样使用它:

<强>同步

Response<Test> response = service.getUser().execute();

<强>异步

service.getUser().enqueue(new Callback<Test>() {
    @Override
    public void onResponse(Response<Test> response) {
        //handle successful response
    }

    @Override
    public void onFailure(Throwable t) {
        //handle error
    }
});

您可以通过致电TestResponse<Test>获取response.body()

如果您使用的是RxJava集成,请使用Observable代替Call

public interface TestService {
    @GET("test")
    Observable<Test> getUser();
}

service.getUser().subscribe(
    user -> ,//do something with your user,
    error -> //something wrong happened
);