How to populate a Spinner from Restful API in Kotlin

In this android kotlin source code example, we are going to populate a Spinner from Restful API in Kotlin.

You can copy and adopt this source code example to your Kotlin android project without reinventing the wheel.

Below is a step by step source code to populate a Spinner from Restful API in Kotlin.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="24dp"
    tools:context=".spinner.SpinnerActivity15">

    <Spinner
        android:id="@+id/spinner"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"/>

</androidx.constraintlayout.widget.ConstraintLayout>

MainActivity.kt

import android.app.ProgressDialog
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.ArrayAdapter
import android.widget.Spinner
import android.widget.Toast
import com.bluapp.kotlinview.R
import com.google.gson.annotations.SerializedName
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.http.GET

class SpinnerActivity15 : AppCompatActivity() {
    private var progressDialog: ProgressDialog? = null
    private var spinner: Spinner? = null
    private var baseUrl: String? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_spinner15)
        spinner = findViewById(R.id.spinner) as Spinner
        baseUrl = "http://dummy.restapiexample.com/"
        fetchData();
    }

    private fun fetchData() {
        progressDialog = ProgressDialog(this@SpinnerActivity15)
        progressDialog!!.setMessage(getString(R.string.loading))
        progressDialog!!.setCancelable(false)
        progressDialog!!.show()
        //Defining retrofit api service
        val retrofit = Retrofit.Builder()
            .baseUrl(baseUrl)
            .addConverterFactory(GsonConverterFactory.create())
            .build()

        val service = retrofit.create<ApiService>(ApiService::class.java!!)
        val call = service.GetEmployeeData()
        //calling the api
        call.enqueue(object : Callback<List<RetrofitGetResponse>> {
            override fun onResponse(call: Call<List<RetrofitGetResponse>>, response: Response<List<RetrofitGetResponse>>) {
                //hiding progress dialog
                progressDialog!!.dismiss()
                //if there is no error
                val responseList = response.body()
                val item = arrayOfNulls<String>(responseList!!.size)
                for(i in 0 until responseList.size){
                    item[i] = responseList.get(i).employeeName
                }
                val arrayadapter = ArrayAdapter(this@SpinnerActivity15, android.R.layout.simple_spinner_item, item)
                spinner?.adapter = arrayadapter
            }
            override fun onFailure(call: Call<List<RetrofitGetResponse>>, t: Throwable) {
                progressDialog!!.dismiss()
                Toast.makeText(applicationContext, t.message, Toast.LENGTH_LONG).show()
            }
        })
    }

    private interface ApiService {
        @GET("api/v1/employees")
        fun GetEmployeeData(): Call<List<RetrofitGetResponse>>
    }

    private inner class RetrofitGetResponse {
        @SerializedName("profile_image")
        var profileImage: String? = null
        @SerializedName("employee_name")
        var employeeName: String? = null
        @SerializedName("employee_salary")
        var employeeSalary: String? = null
        @SerializedName("id")
        var id: String? = null
        @SerializedName("employee_age")
        var employeeAge: String? = null
    }

}

app/build.gradle

implementation 'com.squareup.retrofit2:retrofit:2.4.0'
implementation 'com.squareup.retrofit2:converter-gson:2.4.0'

If you have any question or suggestions kindly use the comment box or you can contact us directly through our contact page below.

Add a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

50% Discounts On Projects

Do you have a custom project with a clear requirements, we are currently giving a 50% discount on all projects.

We will work with you to ensure we deliver what you need.

If you have questions or want to chat with us, you can reach us on Skype (henry.tochi)

Languages and technologies we use - Java, Kotlin, Laravel, Vue, React, Flutter, Swift and more.