source

클래스 예제의 콜어댑터를 작성할 수 없습니다.간단하죠.

goodcode 2022. 9. 19. 23:36
반응형

클래스 예제의 콜어댑터를 작성할 수 없습니다.간단하죠.

SimpleXml에서 retrofit 2.0.0-beta1을 사용하고 있습니다.REST 서비스에서 단순(XML) 리소스를 가져옵니다.SimpleX를 사용한 Simple 객체의 마샬링/언마샬링ML은 정상적으로 동작.

이 코드(변환된 형식 2.0.0 이전 코드)를 사용하는 경우:

final Retrofit rest = new Retrofit.Builder()
    .addConverterFactory(SimpleXmlConverterFactory.create())
    .baseUrl(endpoint)
    .build();
SimpleService service = rest.create(SimpleService.class);
LOG.info(service.getSimple("572642"));

서비스:

public interface SimpleService {

    @GET("/simple/{id}")
    Simple getSimple(@Path("id") String id);

}

다음과 같은 예외가 있습니다.

Exception in thread "main" java.lang.IllegalArgumentException: Unable to create call adapter for class example.Simple
    for method SimpleService.getSimple
    at retrofit.Utils.methodError(Utils.java:201)
    at retrofit.MethodHandler.createCallAdapter(MethodHandler.java:51)
    at retrofit.MethodHandler.create(MethodHandler.java:30)
    at retrofit.Retrofit.loadMethodHandler(Retrofit.java:138)
    at retrofit.Retrofit$1.invoke(Retrofit.java:127)
    at com.sun.proxy.$Proxy0.getSimple(Unknown Source)

가가무 엇뜨 ?뜨? ???은 품로로a로 있습니다.Call동작합니다. 단, 서비스에서는 비즈니스 오브젝트를 유형으로 되돌리고 싶습니다(동기 모드로 동작합니다).

갱신하다

및 추가 의존관계 후.addCallAdapterFactory(RxJavaCallAdapterFactory.create())다른 답변에서 제시된 바와 같이 다음과 같은 오류가 나타납니다.

Caused by: java.lang.IllegalArgumentException: Could not locate call adapter for class simple.Simple. Tried:
 * retrofit.RxJavaCallAdapterFactory
 * retrofit.DefaultCallAdapter$1

Kotlincoroutines의 경우 api service function을 다음과 같이 표시하는 것을 잊어버렸을 때 이 상황이 발생하였습니다.suspend에서 이 CoroutineScope(Dispatchers.IO).launch{}:

사용방법:

    val apiService = RetrofitFactory.makeRetrofitService()

    CoroutineScope(Dispatchers.IO).launch {

        val response = apiService.myGetRequest()

        // process response...

    }

ApiService.kt

interface ApiService {

       @GET("/my-get-request")
       suspend fun myGetRequest(): Response<String>
}

간단한 답변: 서비스 인터페이스로 돌아갑니다.

Retrofit 2.0은 서비스 인터페이스의 프록시 개체를 만드는 방법을 찾고 있는 것 같습니다.다음과 같은 내용을 기입할 수 있습니다.

public interface SimpleService {
    @GET("/simple/{id}")
    Call<Simple> getSimple(@Path("id") String id);
}

,, 이, 이, when, when, when, when, when, when, when, when, when, when, when, when, when, , when, when, when, when, when, when, when, when, when, when, when, when, when, when, when, when, when, when, when, when, when, when, when, when, when, when, when, Call이를 지원하기 위해 A의 개념을 가지고 있으며, 이는 어떻게 적응하는지를 알고 있어야 합니다.Call<Simple>Simple.

「 」의 RxJavaCallAdapterFactory는 반환을 합니다.rx.Observable<Simple>.

은 A/S를 입니다.CallRetrofit의 예상대로입니다.꼭 필요한 경우 a를 쓸 수도 있습니다.

종속성 추가:

compile 'com.squareup.retrofit:retrofit:2.0.0-beta1'
compile 'com.squareup.retrofit:adapter-rxjava:2.0.0-beta1'
compile 'com.squareup.retrofit:converter-gson:2.0.0-beta1'

다음과 같이 어댑터를 만듭니다.

Retrofit rest = new Retrofit.Builder()
    .baseUrl(endpoint)
    .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
    .addConverterFactory(SimpleXmlConverterFactory.create())
    .build();

addCallAdapterFactory () ★★★★★★★★★★★★★★★★★」addConverterFactory ()둘다다 다해해해

서비스:

public interface SimpleService {

    @GET("/simple/{id}")
    Call<Simple> getSimple(@Path("id") String id);

}

Simple로로 합니다.Call<Simple>.

새로운 Retrofit(2.+)에서는 addCallAdapterFactory를 추가해야 합니다.이것은 일반 RxJavaCallAdapterFactory 또는 (Ovservatables의 경우)입니다.두 개 이상 넣어도 될 것 같아요.어떤 것을 사용할지 자동으로 체크합니다.다음의 작업 예를 참조해 주세요.자세한 내용은 이 링크도 참조할 수 있습니다.

 Retrofit retrofit = new Retrofit.Builder().baseUrl(ApiConfig.BASE_URL)
        .addConverterFactory(GsonConverterFactory.create())
        .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
        .build()

를 사용하고 경우는,retrofit2것은 .retrofit2.Call<T>만의 것을 CallAdapter.Factory이치노간단한 코드는 다음과 같습니다.

import retrofit2.Call;
import retrofit2.CallAdapter;
import retrofit2.Retrofit;

import java.lang.annotation.Annotation;
import java.lang.reflect.Type;

public class SynchronousCallAdapterFactory extends CallAdapter.Factory {
    public static CallAdapter.Factory create() {
        return new SynchronousCallAdapterFactory();
    }

    @Override
    public CallAdapter<Object, Object> get(final Type returnType, Annotation[] annotations, Retrofit retrofit) {
        // if returnType is retrofit2.Call, do nothing
        if (returnType.toString().contains("retrofit2.Call")) {
            return null;
        }

        return new CallAdapter<Object, Object>() {
            @Override
            public Type responseType() {
                return returnType;
            }

            @Override
            public Object adapt(Call<Object> call) {
                try {
                    return call.execute().body();
                } catch (Exception e) {
                    throw new RuntimeException(e); // do something better
                }
            }
        };
    }
}

해 주세요.SynchronousCallAdapterFactory복고풍으로 당신의 문제를 해결할 수 있을 것입니다.

Retrofit rest = new Retrofit.Builder()
        .baseUrl(endpoint)
        .addConverterFactory(SimpleXmlConverterFactory.create())
        .addCallAdapterFactory(SynchronousCallAdapterFactory.create())
        .build();

수 .retrofit2.Call.

public interface SimpleService {
    @GET("/simple/{id}")
    Simple getSimple(@Path("id") String id);
}

개조 2에 대한 다음 종속성 추가

 compile 'com.squareup.retrofit2:retrofit:2.1.0'

GSON용

 compile 'com.squareup.retrofit2:converter-gson:2.1.0'

관측 가능한 것

compile 'com.squareup.retrofit2:adapter-rxjava:2.1.0'

XML 의 경우는, 다음의 의존 관계를 포함할 필요가 있습니다.

 compile 'com.squareup.retrofit2:converter-simplexml:2.1.0'

다음과 같이 서비스 콜을 갱신합니다.

final Retrofit rest = new Retrofit.Builder()
    .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
    .addConverterFactory(SimpleXmlConverterFactory.create())
    .baseUrl(endpoint)
    .build();
SimpleService service = rest.create(SimpleService.class);

부정 인수예외:클래스 java.lang의 콜어댑터를 생성할 수 없습니다.물건

간단한 답변:다음과 같은 변경으로 해결했습니다.

ext.retrofit2Version = '2.4.0' -> '2.6.0'
implementation"com.squareup.retrofit2:retrofit:$retrofit2Version"
implementation "com.squareup.retrofit2:adapter-rxjava2:$retrofit2Version"
implementation "com.squareup.retrofit2:converter-gson:$retrofit2Version"

행운을 빌어요

이 경우:

val apiService = RetrofitFactory.makeRetrofitService()

CoroutineScope(Dispatchers.IO).launch {

    val response = apiService.myGetRequest()

    // process response...

}

interface ApiService {

   @GET("/my-get-request")
   suspend fun myGetRequest(): Response<String>
}

에서 suspend는 반드시 ''로 해야 합니다.suspendCorountine의 관리 용이성 때문입니다.자세한 은 이쪽을 봐 주세요.

API 을 "API"로 "API"로 마크합니다.suspend Coroutine Scope 에서 suspend Android 앱, Android 이 느려집니다.Exception in thread "main" java.lang.IllegalArgumentException: Unable to create call adapter for class example.class

Coroutine Call Adapter Factory에서 Coroutines를 사용했는데 실수로 기능을 일시 정지하는 것을 잊었습니다.누군가 도움이 되었으면 좋겠다!

저 같은 경우에는 이걸 이용해서

compile 'com.jakewharton.retrofit:retrofit2-rxjava2-adapter:1.0.0'

이와 함께.

new Retrofit.Builder().addCallAdapterFactory(RxJava2CallAdapterFactory.create())...

다른 것은 아무것도 안 먹혔을 때 문제를 해결했다

RxJava를 사용하고 있지 않다면 RxJava를 개조용으로만 추가하는 것은 의미가 없습니다. 2.5.0 지지하고 있다를 CompletableFuture다른 라이브러리나 어댑터를 추가하지 않고 사용할 수 있습니다.

build.gradle.kts

implementation("com.squareup.retrofit2:retrofit:2.5.0")
implementation("com.squareup.retrofit2:retrofit-converters:2.5.0")

Api.kt

interface Api {
    @GET("/resource")
    fun listCompanies(): CompletableFuture<ResourceDto>
}

사용방법:

Retrofit.Builder()
   .addConverterFactory(SimpleXmlConverterFactory.create())
   .baseUrl("https://api.example.com")
   .build()
   .create(Api::class.java)

이행 중인 사용자, Rx를 사용하지 않는 사용자 또는 동기 콜을 필요로 하는 사용자를 위해 콜의 예를 명확히 하기 위해 콜은 기본적으로 응답을 대체(잘라짐)합니다.즉, 다음과 같습니다.

Response<MyObject> createRecord(...);

된다

Call<MyObject> createRecord(...);

가 아니라

Call<Response<MyObject>> createRecord(...);

(어댑터가 필요합니다)


후, 콜에서는, 「 」, 「 」, 「 」, 「 」를 사용할 수 .isSuccessful실제로 응답을 반환하기 때문입니다.을 사용하다

myApi.createRecord(...).execute().isSuccessful()

또는 다음과 같이 유형(MyObject)에 액세스합니다.

MyObject myObj = myApi.createRecord(...).execute().body();
public interface SimpleService {

  @GET("/simple/{id}")
  Simple getSimple(@Path("id") String id);

}

네트워크와의 통신은 별도의 스레드로 이루어지므로 심플을 변경해야 합니다.

public interface SimpleService {

  @GET("/simple/{id}")
  Call<Simple> getSimple(@Path("id") String id);

}

저 같은 경우에는

com.squareup.retrofit2:adapter-rxjava:2.5.0 //notice rxjava

대신

com.squareup.retrofit2:adapter-rxjava2:2.5.0 //notice rxjava2

쓰셔야 요.com.squareup.retrofit2:adapter-rxjava2:2.5.0「」를 하고 있는 io.reactivex.rxjava2

Callback을 구현하여 onResponse 함수에서 Simple을 얻을 수 있습니다.

public class MainActivity extends Activity implements Callback<Simple> {

    protected void onCreate(Bundle savedInstanceState) {
        final Retrofit rest = new Retrofit.Builder()
                    .addConverterFactory(SimpleXmlConverterFactory.create())
                    .baseUrl(endpoint)
                    .build();
        SimpleService service = rest.create(SimpleService.class);
        Call<Simple> call = service.getSimple("572642");
        //asynchronous call
        call.enqueue(this);

        return true;
    }

    @Override
    public void onResponse(Response<Simple> response, Retrofit retrofit) {
       // response.body() has the return object(s)
    }

    @Override
    public void onFailure(Throwable t) {
        // do something
    }

}

해결책을 찾았습니다. 제 상황에서는ApiInterface.java에서 JAVA에 합니다.MyViewModel.ktKOTLIN이 되다.

  1. 은 것은입니다.ApiInterface.java

    @GET(상수).CONNECTION)을 호출합니다.< com . example . kt . model 。ConnectionResponse > ConnectionKt();

  2. 클래스를 새로 . 코틀린는 코틀린 클래스입니다.ApiTemporary.kt

    클래스 ApiTemporary(프라이빗 val apiInterface:ApiInterface = RetrofitClient . getRetrofitInstance() . create ( ApiInterface : : class . java ) ,

    suspend fun getConnectionKt(): 응답 {return apiInterface.ConnectionKt().awaitResponse() } }

  3. 그래서 마지막으로MyViewModel.kt, 이렇게 할 수 있습니다.

val data = withContext(ioDispatcher) {val result = apiTemporary.getConnectionKt() if (result.isSuccessful) {Resource.Success(result.body())} 이외의 경우 {Resource.에러("서버 에러.다시 시도하십시오" ) } } _connection.value = 데이터

그래서...ApiTemporaryJava에서 Coroutines를 사용하는 Kotlin으로 변환하는 데 도움이 됩니다.

gradle에서 retrofit 버전을 2.9.0으로 업데이트하여 해결했습니다.

API 인터페이스가 Response 개체를 반환하는 경우 API 인터페이스에 suspend 함수를 추가하는 것을 잊었을 수 있습니다.

API 인터페이스

interface WeatherAPI {
    @GET("/data/2.5/weather")
    suspend fun getWeatherInfo(
        @Query("q") query: String
    ): Response<WeatherResponse>
}

저장소

class WeatherRepositoryImpl @Inject constructor(
private val weatherAPI: WeatherAPI
) : WeatherRepository {
    override suspend fun getWeatherInfo(query: String): Resource<WeatherResponse> {
        try {
            val response = weatherAPI.getWeatherInfo(query)
            if (response.isSuccessful) {
                response.body()?.let {
                    return Resource.success(it)
                } ?: return Resource.error("Unknown error occurred", null)
            } else {
                return Resource.error("Unknown error occured", null)
            }
        } catch (e: Exception) {
            return Resource.error("Please check your internet connection", null)
        }
    }

}

이 문제를 수정한 방법은 응용 프로그램그래들 파일에 이 문제를 추가하는 것입니다.설정이 설정되어 있지 않으면 충돌이 발생합니다.아마 라이브러리의 안정된 릴리스에서 이 문제가 수정될 것입니다.

configurations {
    compile.exclude group: 'stax'
    compile.exclude group: 'xpp3'
}

dependencies {
    compile 'com.squareup.retrofit:retrofit:2.0.0-beta1'
    compile 'com.squareup.retrofit:converter-simplexml:2.0.0-beta1'
}

다음과 같이 어댑터를 만듭니다.

  Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(endPoint)
            .addConverterFactory(SimpleXmlConverterFactory.create())
            .build();

도움이 됐으면 좋겠다!

언급URL : https://stackoverflow.com/questions/32269064/unable-to-create-call-adapter-for-class-example-simple

반응형