Skip to content

Instantly share code, notes, and snippets.

@penguinshunya
Created September 1, 2021 12:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save penguinshunya/e387d3b61b8d92b62082099dbd9ba72a to your computer and use it in GitHub Desktop.
Save penguinshunya/e387d3b61b8d92b62082099dbd9ba72a to your computer and use it in GitHub Desktop.
package com.penguinshunya.myapplication
import android.content.ContentValues
import android.content.Context
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val helper = SampleDBHelper(applicationContext, "SampleDB", null, 1)
try {
val db = helper.writableDatabase
val values = ContentValues()
values.put("id", 2)
values.put("name", "takaya")
values.put("type", 12345)
db.insertOrThrow("SampleTable", null, values)
} catch (e: Exception) {
Log.e("insertData", e.toString())
}
try {
val db = helper.readableDatabase
val sql = "SELECT id, name, type FROM SampleTable"
val c = db.rawQuery(sql, null)
while (c.moveToNext()) {
Log.e("Value", c.getString(1))
}
} catch (e: Exception) {
}
}
}
private class SampleDBHelper(
context: Context,
databaseName: String,
factory: SQLiteDatabase.CursorFactory?,
version: Int
) : SQLiteOpenHelper(context, databaseName, factory, version) {
override fun onCreate(database: SQLiteDatabase?) {
database?.execSQL("create table if not exists SampleTable (id text primary key, name text, type integer)");
}
override fun onUpgrade(database: SQLiteDatabase?, oldVersion: Int, newVersion: Int) {
if (oldVersion < newVersion) {
database?.execSQL("alter table SampleTable add column deleteFlag integer default 0")
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment