Simple example with Retrofit Gson and Enum types in Android
The dependencies for this example:
implementation 'com.google.code.gson:gson:2.8.5' implementation 'com.squareup.retrofit2:retrofit:2.5.0' implementation 'com.squareup.retrofit2:converter-gson:2.5.0' implementation 'com.squareup.okhttp3:logging-interceptor:3.6.0'
We will retrieve a list of clothes, with each cloth containing a string and an enum type. Here are the data models.
Cloth.kt
data class Cloth (
@SerializedName("size") val clothSize : ClothSize,
@SerializedName("cloth") val cloth : String
)
ColthSize.kt
enum class ClothSize {
SMALL,
MEDIUM,
LARGE
}
The Retrofit api client for fetching the list of clothes from the internet.
ApiClient.kt
import retrofit2.Call
import retrofit2.http.GET
interface ApiClient {
// https://api.jsonbin.io/b/5cad463a4b652413968069a2
// https://api.myjson.com/bins/17n6pk
@GET("bins/17n6pk")
fun getClothes(): Call>
}
The utility class for creating Retrofit instance. RestUtil.kt
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
class RestUtil private constructor() {
private val API_BASE_URL = "https://api.myjson.com/"
// private val API_BASE_URL = "https://api.jsonbin.io/"
val retrofit: Retrofit
init {
val interceptor = HttpLoggingInterceptor()
interceptor.level = HttpLoggingInterceptor.Level.BODY
val httpClient = OkHttpClient.Builder().addInterceptor(interceptor).build()
val builder = Retrofit.Builder()
.baseUrl(API_BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
retrofit = builder.client(httpClient).build()
}
companion object {
private var self: RestUtil? = null
val instance: RestUtil
get() {
if (self == null) {
synchronized(RestUtil::class.java) {
if (self == null) {
self = RestUtil()
}
}
}
return self!!
}
}
}
Finally, the activity class for putting all of the above together and get the list of clothes from an url.
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
fab.setOnClickListener {
fetchClothes()
}
}
private fun fetchClothes() {
tv_clothes.text = ""
val client = RestUtil.instance.retrofit.create(ApiClient::class.java)
val call = client.getClothes()
call.enqueue(object : Callback> {
override fun onResponse(call: Call>, response: Response>) {
if (response.body() != null) {
val clothes = response.body()
var stringBuilder = StringBuilder("")
clothes?.forEach {
stringBuilder.append(it.cloth)
stringBuilder.append(" ")
stringBuilder.append(it.clothSize)
stringBuilder.append("\n")
}
tv_clothes.text = stringBuilder.toString()
}
}
override fun onFailure(call: Call>, t: Throwable) {
t.printStackTrace()
}
})
}
}
Don’t forget to add the internet permission in the manifest file.
Search within Codexpedia
Custom Search
Search the entire web
Custom Search
Related Posts