Adding / Query / Parse SQLite using Anko

1.7k views Asked by At

tl;dr: I'm having issues trying to get my code to work, now I can create the database using Anko and insert the columns but when I try to insert the data and when I open the database on sqliteman my columns are empty I also don't know how to retrieve the data in strings/Int to send to a View

This apparently works fine I can see my database created with all the columns with the right name

class MySqlHelper(ctx: Context) : ManagedSQLiteOpenHelper(ctx, "db_main") {

companion object {
    private var instance: MySqlHelper? = null

    @Synchronized
    fun getInstance(ctx: Context): MySqlHelper {
        if (instance == null) {
            instance = MySqlHelper(ctx.applicationContext)
        }
        return instance!!
    }
}


override fun onCreate(db: SQLiteDatabase) {
    db.createTable("db_main", true,
            "_id" to INTEGER + PRIMARY_KEY + AUTOINCREMENT + NOT_NULL,
            "name" to TEXT,
            "day" to INTEGER)

}

override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {
       }

// Access property for Context
val Context.database: MySqlHelper
    get() = getInstance(applicationContext)

}

This should work but it doesn't Although I have all the columns in the database and I don't get any error messages they're not being added

The code below is called in MainActivity

val db = MySqlHelper(this)


fun addtosqllite(title: String, datepicker: DatePicker) {

db.use {
        insert("db_main",
                "_id" to 1,
                "name" to title,
                "day" to  datepicker.dayOfMonth)
     }
}

I have no idea how to do this I need to retrieve the data from the database. I've been Reading the documentation but I don't know how to implement this

Let's say that I have three columns _id, name and day I was doing something like

db.select("main_db","_id","name","day").exec {
parseSingle //something goes here to send the data to String/Int
}
1

There are 1 answers

1
Halima On

I hope it's not too late. You can try this :

database.use {
  select("main_db", "_id", "name","day").exec {
   parseList( object : MapRowParser<Map<String, Any?>> {
    override fun parseRow(columns: Map<String, Any?>): Map<String, Any?> {
      Log.e("Your result", columns.toString())
        return columns
      }
    }
   )
 }