Skip to main content

How to populate a Spinner with dynamic data from a database in Kotlin Android

How to populate a Spinner with dynamic data from a database in Kotlin Android.

Here's a detailed step-by-step tutorial on how to populate a Spinner with dynamic data from a database in Kotlin Android.

Step 1: Set up your project

  • Open Android Studio and create a new project.
  • Choose an appropriate name for your project and select the minimum SDK version.
  • Click on "Finish" to create the project.

Step 2: Add necessary dependencies

  • Open the build.gradle (Module: app) file.
  • Add the following dependency under the dependencies section: implementation 'androidx.recyclerview:recyclerview:1.2.1'
  • Sync the project to add the dependency.

Step 3: Create a layout file for the Spinner

  • Right-click on the "res" directory and select "New -> Android resource file".
  • Enter a suitable name for the resource file, such as "spinner_item".
  • Choose "layout" as the Resource type.
  • Click on "OK" to create the file.
  • In the spinner_item.xml file, add a TextView to display the items in the Spinner.
    <TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@android:id/text1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:textSize="16sp"
    android:textColor="@android:color/black"
    android:padding="10dp" />

Step 4: Create a layout file for the Activity

  • Open the activity_main.xml file.
  • Add a Spinner element to the layout.
    <Spinner
    android:id="@+id/spinner"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="16dp" />

Step 5: Create a data model class

  • Right-click on the package name in the Project pane and select "New -> Kotlin Class".
  • Give the class a suitable name, such as "Item".
  • Add the following code to define the properties of the data model.
    data class Item(val id: Int, val name: String)

Step 6: Create a database helper class

  • Right-click on the package name in the Project pane and select "New -> Kotlin Class".

  • Give the class a suitable name, such as "DatabaseHelper".

  • Add the following code to create a SQLite database and retrieve data from it.

    class DatabaseHelper(context: Context) : SQLiteOpenHelper(context, DATABASE_NAME, null, DATABASE_VERSION) {
    companion object {
    private const val DATABASE_VERSION = 1
    private const val DATABASE_NAME = "items.db"
    private const val TABLE_NAME = "items"
    private const val COLUMN_ID = "id"
    private const val COLUMN_NAME = "name"
    }

    override fun onCreate(db: SQLiteDatabase) {
    val createTable = "CREATE TABLE $TABLE_NAME ($COLUMN_ID INTEGER PRIMARY KEY, $COLUMN_NAME TEXT)"
    db.execSQL(createTable)
    }

    override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {
    db.execSQL("DROP TABLE IF EXISTS $TABLE_NAME")
    onCreate(db)
    }

    fun getAllItems(): List<Item> {
    val items = mutableListOf<Item>()
    val selectQuery = "SELECT * FROM $TABLE_NAME"
    val db = this.readableDatabase
    val cursor = db.rawQuery(selectQuery, null)

    if (cursor.moveToFirst()) {
    do {
    val id = cursor.getInt(cursor.getColumnIndex(COLUMN_ID))
    val name = cursor.getString(cursor.getColumnIndex(COLUMN_NAME))
    items.add(Item(id, name))
    } while (cursor.moveToNext())
    }

    cursor.close()
    db.close()

    return items
    }
    }

Step 7: Populate the Spinner with data from the database

  • Open the MainActivity.kt file.

  • Declare a variable to hold the reference to the Spinner.

  • Initialize the Spinner in the onCreate() method.

  • Create an instance of the DatabaseHelper class.

  • Retrieve the data from the database using the getAllItems() method.

  • Create an ArrayAdapter to bind the data to the Spinner.

  • Set the ArrayAdapter as the adapter for the Spinner.

  • Handle item selection if needed.

    class MainActivity : AppCompatActivity() {
    private lateinit var spinner: Spinner
    private lateinit var databaseHelper: DatabaseHelper

    override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    spinner = findViewById(R.id.spinner)
    databaseHelper = DatabaseHelper(this)

    val items = databaseHelper.getAllItems()
    val adapter = ArrayAdapter<Item>(this, android.R.layout.simple_spinner_item, items)
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
    spinner.adapter = adapter

    spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
    override fun onItemSelected(parent: AdapterView<*>, view: View?, position: Int, id: Long) {
    val selectedItem = parent.getItemAtPosition(position) as Item
    // Handle item selection
    }

    override fun onNothingSelected(parent: AdapterView<*>) {
    // Handle no selection
    }
    }
    }
    }

Step 8: Run the app

  • Connect your Android device or emulator.
  • Click on the "Run" button in Android Studio to build and run the app.
  • The Spinner should now be populated with the data from the database.

Congratulations! You have successfully populated a Spinner with dynamic data from a database in Kotlin Android.