Im trying to setup Retrofit2 with suspend functions but I am having unexpected error while in offline mode (all good in online mode).
ApiService:
interface ApiService {
#GET("v2/153")
suspend fun fetchData(): Response<DataModel>
}
Retrofit Client:
fun provideDefaultOkhttpClient(context: Context): OkHttpClient {
val cacheSize = (5 * 1024 * 1024).toLong()
return OkHttpClient.Builder()
.cache(Cache(context.cacheDir, cacheSize))
.build()
}
fun provideRetrofit(client: OkHttpClient): Retrofit {
return Retrofit.Builder()
.client(client)
.baseUrl(BASE_URL)
.addConverterFactory(MoshiConverterFactory.create())
.build()
}
fun provideApiService(retrofit: Retrofit): ApiService =
retrofit.create(ApiService::class.java)
DataRepository:
class DataRepository(private val api: ApiService) {
suspend fun getData(): List<DataModel>? {
val myData = api.fetchData()
return if (myData.isSuccessful) {
myData.body()
} else {
null
}
}
}
While debugging the app I see the DataRepository->api.fetchData() being called, and from there it hangs and I get the following error:
2019-06-28 10:35:46.136 10876-10876/com.myapp.name.debug E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.myapp.name.debug, PID: 10876
What am I missing? Or am I just wrongly using suspend function to retrieve data?
Related
I have a Hilt module to provide Retrofit API in my app like so:
#Module
#InstallIn(SingletonComponent::class)
object NetworkDataModule {
#Provides
#Singleton
fun provideOkHttpClient(): OkHttpClient {
return OkHttpClient.Builder()
.addInterceptor(
HttpLoggingInterceptor().apply {
level = HttpLoggingInterceptor.Level.BODY
}
)
.build()
}
#Provides
#Singleton
fun provideMyApi(client: OkHttpClient): MyApi {
return Retrofit.Builder()
.baseUrl(MyApi.BASE_URL)
.addConverterFactory(MoshiConverterFactory.create())
.client(client)
.build()
.create()
}
}
And it is my API interface:
interface MyApi {
#GET("search")
suspend fun search(): searchDto
companion object {
const val BASE_URL = "https://myapi.com/"
}
}
The question is how the Retrofits create() extension function knows which class should it return despite I did not pass any information about the MyApi interface to it. The create function implementation is this:
inline fun <reified T> Retrofit.create(): T = create(T::class.java)
How does create(T::class.java) return MyApi in spite of I did not provide any type for T?
My retrofit version is 2.9.0
I have weather api to parse data for 10 days
All it's good , but I have problem with retrofit now , I have app crashes , my URL(with API) have / in the end.
But still don't working.
Also I have dependency injection for retrofit.
Goal is to get data from api.
Hope , that you will help me to resolve this problem.
package const
const val BASE_URL = "https://api.weatherapi.com/v1/forecast" +
".json?key=a9f9d57b6e064f16b28141346231001&q=London&days=10&aqi=no&alerts=no/" // error here
const val apikey = "a9f9d57b6e064f16b28141346231001"
const val WeatherDays = 10
interface WeatherServiceAPI {
#GET("forecast.json")
suspend fun Weatherday(
#Query("days") days : Int
) : WeatherResponse
#GET("forecast.json")
suspend fun searchcitybycoord(#Query("lat")lat:String) : List<WeatherLocationDTO>
#GET("forecast.json")
suspend fun searchingbyCity(#Query("q") name: String) : List<WeatherLocationDTO>
companion object{
operator fun invoke(
connectivityInterceptor: Interceptor
):WeatherServiceAPI{
val requestInterceptor = Interceptor{
chain -> val url = chain.request()
.url
.newBuilder()
.addQueryParameter("key", apikey)
.build()
val request = chain.request()
.newBuilder()
.url(url)
.build()
return#Interceptor chain.proceed(request)
}
val okHttpClient = OkHttpClient.Builder()
.addInterceptor(requestInterceptor)
.addInterceptor(connectivityInterceptor)
.build()
return Retrofit.Builder()
.client(okHttpClient)
.baseUrl("https://api.weatherapi.com/v1/") // error line
.addCallAdapterFactory(CoroutineCallAdapterFactory())
.addConverterFactory(GsonConverterFactory.create())
.build()
.create(WeatherServiceAPI::class.java)
}
}
}
#Provides
#Singleton
fun providerepository(api:WeatherServiceAPI):ForecastRepository{
return ForecastRepositoryImpl(api)
}
#Provides
#Singleton
fun provideWeatherApiService(retrofit: Retrofit) =
retrofit.create(WeatherServiceAPI::class.java)
#Provides
#Singleton
fun provideRetrofit ( okHttpClient: OkHttpClient) = Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())
.baseUrl(BASE_URL)
.client(okHttpClient)
.build()
#Provides
#Singleton
fun provideOkhttpClient(interceptor: Interceptor): OkHttpClient {
val httpBuilder = OkHttpClient.Builder().addInterceptor(interceptor)
return httpBuilder.build()
}
#Provides
#Singleton
fun provideinterceptor():Interceptor{
return Interceptor {
val request =it.request().newBuilder()
val actualRequest = request.build()
it.proceed(actualRequest)
}
}
Given what else you have in the code, your base URL should be https://api.weatherapi.com/v1/.
forecast.json comes from the #GET annotations, and the query parameters will need to come from #Query-annotated parameters to your Retrofit interface functions.
I have an interface called LoginService which is used with Retrofit. There was no accessToken before the user login. When the user has logged in, the LoginService Instance should be updated with acessToken so that the user could log out from the app. The problem is that LoginService class is not updated even though it is not declared as #Singleton. If the user has closed the app and reopen it again, the LoginService got updated and therefore he could log out of the app. How can I reinitialize the LoginService instance as soon as the accessToken has been updated?
The key here is not the reinitialize the instance but to create a separate service whenever the user logs in.
you need to have two different interfaces one for API's pre-login and other for post login.
So one would be Authapi.kt and the other would be Api.kt
So first we need to create OkHttpBuilder for each service,
#Provides
#Singleton
#Named(NetModule.NO_AUTH_CLIENT)
fun provideNoAuthOkHttpClient(
okHttpClientBuilder: OkHttpClient.Builder
): OkHttpClient {
return okHttpClientBuilder.build()
}
#Provides
#Singleton
#Named(NetModule.AUTH_CLIENT)
fun provideAuthOkHttpClient(
okHttpClientBuilder: OkHttpClient.Builder,
tokenInterceptor: NetworkInterceptor
): OkHttpClient {
return okHttpClientBuilder.addInterceptor(tokenInterceptor).build()
}
Network Interceptor is the class where you update your access token for API.
NetworkInterceptor.kt
class NetworkInterceptor #Inject constructor(
val context: Context,
serverBaseUrl: String,
val moshi: Moshi,
val preferences: PreferenceUtility
) : Interceptor {
private fun Request.Builder.setDefaultHeaders(): Request.Builder {
addHeader("App_version_code", BuildConfig.VERSION_CODE.toString())
addHeader("App_version_name", BuildConfig.VERSION_NAME)
addHeader("Mobile_model", Build.MODEL.toString())
addHeader("OS_version", Build.VERSION.SDK_INT.toString())
addHeader("OS_version_release", Build.VERSION.RELEASE.toString())
if (preferences.customerId != -1L)
addHeader("Client_id", preferences.customerId.toString())
return this
}
private fun makeRequestWithAuthTokenAndTimeStamp(request: Request) = request.newBuilder()
.setDefaultHeaders()
.apply {
val oldHeader = request.header("Authorization")
if (oldHeader.isNullOrBlank()) {
val token = if (preferences.authToken.isBlank() || !preferences.customerAuthenticated) BuildConfig.ANONYMOUS_TOKEN else preferences.authToken
addHeader("Authorization", "Bearer $token")
}
}
.url(request.url())
.method(request.method(), request.body())
.build()
override fun intercept(chain: Interceptor.Chain): Response {
val request = chain.request()
// ADD THE TOKEN'S OVER HERE
var response =
chain.proceed(makeRequestWithAuthTokenAndTimeStamp(request))
//You can also add refersh logic here.
return response
}
}
And you NetworkModule.kt will be
#Provides
#Singleton
#Named(NetModule.NO_AUTH_CLIENT)
fun provideNoAuthInterceptorRetrofit(
moshi: Moshi,
#Named(NetModule.NO_AUTH_CLIENT) okHttpClient: OkHttpClient,
debugPreferenceUtility: DebugPreferenceUtility
): Retrofit {
return Retrofit.Builder()
.addConverterFactory(MoshiConverterFactory.create(moshi))
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.baseUrl(debugPreferenceUtility.serverBaseUrl)
.client(okHttpClient)
.build()
}
#Provides
#Singleton
#Named(NetModule.AUTH_CLIENT)
fun provideAuthInterceptorRetrofit(
moshi: Moshi,
#Named(NetModule.AUTH_CLIENT) okHttpClient: OkHttpClient,
debugPreferenceUtility: DebugPreferenceUtility
): Retrofit {
return Retrofit.Builder()
.addConverterFactory(MoshiConverterFactory.create(moshi))
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.baseUrl(debugPreferenceUtility.serverBaseUrl)
.client(okHttpClient)
.build()
}
#Provides
#Singleton
fun provideApi(#Named(AUTH_CLIENT) retrofit: Retrofit) = retrofit.create(Api::class.java)
#Provides
#Singleton
fun provideAuthApi(#Named(NO_AUTH_CLIENT) retrofit: Retrofit) = retrofit.create(AuthApi::class.java)
So the API's that will be used pre-login will be placed inside AuthApi.kt
like send OTP etc and all the rest API will be placed inside Api.kt and Network Interceptor will take care of adding token.
I newbie on kotlin, its my firts app test. I trying to do a retrofit call (POST) but i get sintax error on create code.
My syntax error: no type arguments expected for CallBack
this is my doLogin function on presenter layer (i got error here):
override fun doLogin() {
val call = RetrofitInitializer().loginApiContract().login()
call.enqueue(object: Callback<UserAccount> {
override fun onResponse(call: Call<UserAccount>?,
response: Response<UserAccount) {
}
override fun onFailure(call: Call<UserAccount>?,
t: Throwable?) {
}
})
}
and that is my retrofit initializer:
class RetrofitInitializer {
private val retrofit = Retrofit.Builder()
.baseUrl("http://192.168.0.23:8080/")
.addConverterFactory(GsonConverterFactory.create())
.build()
fun loginApiContract() : LoginApiContract{
return retrofit.create(LoginApiContract::class.java)
}
}
that is my interface of call:
interface LoginApiContract {
#POST("login")
fun login() : Call<UserAccount>
#GET("statements")
fun getStatements()
}
Best practice with kotlin - use rxjava calladapter factory.
Try to add dependency
compile "com.squareup.retrofit2:adapter-rxjava2:"
and add call adapter factory
private val retrofit = Retrofit.Builder()
.baseUrl("http://192.168.0.23:8080/")
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.build()
Help solve the problem!(((I have 3 modules for DI. There is a retrofit object in natworkModule, all viewModels in viewModelModule, and all requests to the server in respositoryModule. I did everything according to the documentation, but I cannot find this error in Google. Thank you in advance!!! Sorry for my english!)
class App : Application(){
override fun onCreate() {
super.onCreate()
startKoin(this, listOf(natworkModule, viewModelModule,repositoryModule))
}
}
var natworkModule = module {
single { createOkHttpClient() }
single { createApiService<ApiService>(get () ,getProperty(SERVER_URL))
}
}
const val SERVER_URL = "https://api.github.com/"
fun createOkHttpClient() : OkHttpClient{
val httpLoggingInterceptor = HttpLoggingInterceptor()
httpLoggingInterceptor.level = HttpLoggingInterceptor.Level.BASIC
return OkHttpClient.Builder()
.connectTimeout(60L, TimeUnit.SECONDS)
.readTimeout(60L, TimeUnit.SECONDS)
.addInterceptor(httpLoggingInterceptor).build()
}
inline fun <reified T> createApiService(okHttpClient: OkHttpClient, url: String): T {
val retrofit = Retrofit.Builder()
.baseUrl(url)
.client(okHttpClient)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(LiveDataCallAdapterFactory()).build()
return retrofit.create(T::class.java)
}
var repositoryModule = module {
factory<TestRepository> {
TestRepositoryImpl(get())
}
}
var viewModelModule = module {
viewModel {
TestViewModel(get())
}
}
Problem was in this constant value ->
SERVER_URL = "https://api.github.com/"
Koin could not find it. Therefore there was an exception. Thanks to all!!!