Skip to content

Instantly share code, notes, and snippets.

@LeonidIvankin
Created May 14, 2022 11:26
Show Gist options
  • Save LeonidIvankin/138a4088d5baeeab127539e1da6c5e4b to your computer and use it in GitHub Desktop.
Save LeonidIvankin/138a4088d5baeeab127539e1da6c5e4b to your computer and use it in GitHub Desktop.
package com.leonidivankin.draftsandroid.articles.db
import android.content.ContentValues
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper
import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
class SQLiteOpenHelperActivity : AppCompatActivity() {
private val db by lazy {
object : SQLiteOpenHelper(this, "colors_db", null, 1) {
override fun onCreate(db: SQLiteDatabase) {
db.execSQL("CREATE TABLE $TABLE_NAME (_id INTEGER PRIMARY KEY AUTOINCREMENT, color TEXT)")
}
override fun onUpgrade(db: SQLiteDatabase?, oldVersion: Int, newVersion: Int) {}
}.readableDatabase
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
Thread{
insert( "green")
insert( "red")
insert( "blue")
get()
}.start()
}
private fun insert(color: String) {
val contentValues = ContentValues()
contentValues.put(COLUMN_NAME, color)
db.insert(TABLE_NAME, null, contentValues)
}
private fun get() {
val cursor = db.query(TABLE_NAME, arrayOf("_id", COLUMN_NAME), null, null, null, null, null)
var i = 0
while (!cursor.isLast) {
cursor.moveToPosition(i)
val id = cursor.getInt(0)
val color = cursor.getString(1)
Log.d("DbExample", "$id $color")
i++
}
}
override fun onDestroy() {
super.onDestroy()
db.close()
}
companion object {
const val TABLE_NAME = "colors"
const val COLUMN_NAME = "color"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment