SQLite Type Mismatch Error

I am following this tutorial from Android SQLite Database in Kotlin - GeeksforGeeks <<

The tutorial is outdated, so I had to make a few changes to the code.

The idea is to create a simple SQLite DB and use it to store and retrieve data.

The MainActivity.kt code that leads to an error is given below:

class MainActivity : AppCompatActivity(){
    override fun onCreate(savedInstanceState: Bundle?) {

        findViewById<Button>(R.id.addData).setOnClickListener {
            val db = DBHelper(this, null)
            val name = findViewById<EditText>(R.id.enterName).text.toString()
            val age = findViewById<EditText>(R.id.enterAge).text.toString()

            db.addName(name, age)

            Toast.makeText(this, name + "added to database ", +Toast.LENGTH_LONG).show()


        val printD = findViewById<Button>(R.id.printData) as Button

            val db = DBHelper(this,null)
            val cursor = db.getName()
            val nameList = findViewById<TextView>(R.id.nameList) as TextView
            val ageList = findViewById<TextView>(R.id.ageList) as TextView


                nameList.append(cursor.getString(cursor.getColumnIndex(DBHelper.NAME_COL)) + "\n")
                ageList.append(cursor.getString(cursor.getColumnIndex(DBHelper.AGE_COL)) + "\n")


The part which actually throws the error is given below:

   fun addName(name: String, age: String){
        val values = ContentValues()

        values.put(NAME_COL, name)
        values.put(AGE_COL, age)

        val db = this.writableDatabase

        return db.rawQuery("SELECT * from "+ TABLE_NAME, Unit)

The error I get are:

Type mismatch: inferred type is Cursor! but Unit was expected and
Type mismatch: inferred type is Unit but Array<(out) String!>! was expected

This is my first time working with Android … so I am at a loss to understand where things are going wrong.

Any help is appreciated.


Just purely looking at your syntax, I think your addName function is wrong.

Do you actually want to return a value from addName? The signature indicates no return type (or rather Unit, which is equivalent to not returning anything). So maybe the return keyword on the last line is causing problems. Try removing that, and see if it’s happier.

Also, why are you passing Unit as the second argument to db.rawQuery()? (I don’t know what that function does, but passing Unitas the second argument seems very weird to me.)