Created
September 1, 2021 12:49
-
-
Save penguinshunya/e387d3b61b8d92b62082099dbd9ba72a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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