改进2类文件问题

问题描述 投票:0回答:4

我在申请中使用改装2时遇到了一个问题。

public static Retrofit getClient(Context context)
{

    if (okHttpClient == null)
        initOkHttp(context);

    if (retrofit == null)
    {
        retrofit = new Retrofit.Builder()
                .baseUrl(CaselotREST.CASELOT_BASEURL)
                .client(okHttpClient)
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .build();
    }
    return retrofit;
}

当我尝试编译项目时出现以下错误。

错误:无法访问reofofit类文件以找不到retrofit2.Retrofit

java android retrofit2 rx-java2
4个回答
3
投票

我已经弄清楚了。问题源于我们的Android应用程序中代码库的模块化。我的android应用程序中有很多模块,每个模块都有依赖项。改造的依赖关系,其中Webapi模块但不在主app模块中。要解决此问题,请将以下内容添加到主gradle文件中

implementation 'com.squareup.retrofit2:converter-gson:2.2.0'
implementation 'com.squareup.retrofit2:retrofit:2.2.0'
implementation 'com.squareup.retrofit2:adapter-rxjava2:2.2.0'

1
投票

确保您已在项目的build.gradle文件中添加了改装依赖项。

implementation 'com.squareup.retrofit2:retrofit:2.5.0'

0
投票

如果您之前使用的是Retrofit 1.x并且现在继续使用Retrofit 2,则可以在gradle文件中添加此行

implementation 'com.squareup.retrofit2:retrofit:2.5.0'

还要确保您拥有AndroidManifest文件所需的权限

  <uses-permission android:name="android.permission.INTERNET" />

如果你有兴趣使用RXJavaRetrofit,你可以查看这个link作为教程。

    //example 
    Gson gson = new GsonBuilder()
            .setLenient()
            .create();

    Retrofit build = new Retrofit.Builder()
            .baseUrl(BuildConfig.BASE_URL)
            .addConverterFactory(GsonConverterFactory.create(gson))
            .client(unsafeOkHttpClient)
            .build();

欢呼,如果这对你有帮助。


0
投票

如果使用RxJava2进行改造,则需要这样的东西。为gson和retrofit添加依赖项,如果你在改装api服务中使用rxjava observable,那么适配器就会导入。

/* retrofit, gson */
implementation 'com.squareup.retrofit2:retrofit:2.4.0'
implementation 'com.squareup.retrofit2:adapter-rxjava2:2.3.0'
implementation 'com.squareup.retrofit2:converter-gson:2.4.0'
implementation 'com.squareup.okhttp3:logging-interceptor:3.8.1'
implementation 'com.squareup.retrofit2:converter-scalars:2.4.0'

那么你的构建器看起来像这样:

 Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(Constants.BASE_API_URL)
            .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
            .addConverterFactory(GsonConverterFactory.create())
            .client(okHttpClient)
            .build();

哪里,

okHttpClient = new OkHttpClient.Builder().build();

然后你可以创建服务,

retrofit.create(RetrofitAPIService.class);

您的RetrofitAPIService将保持API实现类似于此:

@Headers("Content-Type: application/json")
@POST("v1/login/")
Observable<ApiResponse> userLogin(
        @Body String body
);
© www.soinside.com 2019 - 2024. All rights reserved.