Vahid
September 17, 2023, 8:16pm
1
I was getting the following error when I switched to Moshi converter and hoping that it would be able to handle FlickrResponse through fetchPhotos method.
FATAL EXCEPTION: main
Process: com.bignerdranch.android.photogallery, PID: 30598
java.lang.IllegalArgumentException: Unable to create converter for class com.bignerdranch.android.photogallery.api.FlickrResponse
for method FlickrApi.fetchPhotos
Looks Seems like you need to create a Kotlin adapter first and pass it on the MoshiConverterFactory’s create method as a parameter:
init {
// Kotlin reflection adapter
val moshi = Moshi.Builder()
.add(KotlinJsonAdapterFactory())
.build()
val retrofit: Retrofit = Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(MoshiConverterFactory.create(moshi))
.build()
flickrApi = retrofit.create(FlickrApi::class.java)
}
Hope it helps others who have ran into this!
hrl
December 4, 2023, 10:05pm
2
Did you comment out those lines “@JsonClass (generateAdapter = true)”? This is what is giving me the issue.
And which package is KotlinJsonAdapterFactory from? I’ve got a unresolved reference here.
hrl
December 6, 2023, 12:40am
3
Okay, I solved the issue. And here’s more detailed:
I comment out all @JsonClass (generateAdapter = true) line
Added another implementation for build.gradle:
implementation("com.squareup.moshi:moshi-kotlin:1.14.0")
initialize the moshi, retrofit and flickerAPI outside of init and it works.
Here’s my PhotoRepository.kt:
package com.bignerdranch.android.photogallery
import com.bignerdranch.android.photogallery.api.FlickrApi
import com.bignerdranch.android.photogallery.api.GalleryItem
import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory
import com.squareup.moshi.Moshi
import retrofit2.Retrofit
import retrofit2.converter.moshi.MoshiConverterFactory
import retrofit2.create
private const val BASE_URL = "https://api.flickr.com/"
class PhotoRepository {
private val moshi = Moshi.Builder()
.add(KotlinJsonAdapterFactory())
.build()
private val retrofit = Retrofit.Builder()
.addConverterFactory(MoshiConverterFactory.create(moshi))
.baseUrl(BASE_URL)
.build()
private val flickrApi: FlickrApi = retrofit.create()
suspend fun fetchPhotos(): List<GalleryItem> =
flickrApi.fetchPhotos().photos.galleryItems
}