Search code examples
androiddatabasesqlitekotlinandroid-sqlite

How to make record just one time in SQLiteDatabase?


I'm an android developer. Is there a way to put data into SQLiteDatabase only once when the app is running? In my MainActivity, duplicate data accumulates continuously when running the app. I want the data to be added only once when the user launches the app.

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val db = MyDatabaseHelper(this)

        db.createRamen(MyData(1))
        db.createRamen(MyData(2))
        db.createRamen(MyData(3))
        db.createRamen(MyData(4))
        ...
    }
...
}

[EDIT]

class RamenDatabaseHelper(var context: Context) : SQLiteOpenHelper(context, DATABASE_NAME, null, DATABASE_VERSION) {
    companion object {
        private val DATABASE_NAME = "MyDatabase"
        private val DATABASE_VERSION = 1
        private val TABLE_NAME = "MyTable"
    }

    private val KEY_ID = "id"
    private val KEY_NAME = "name"

    override fun onCreate(db: SQLiteDatabase?) {
        val CREATE_TABLE = "CREATE TABLE IF NOT EXISTS $TABLE_NAME($KEY_ID INTEGER PRIMARY KEY, $KEY_NAME TEXT)"
        db!!.execSQL(CREATE_TABLE)
    }

    override fun onUpgrade(db: SQLiteDatabase?, old: Int, new: Int) {
        if (old >= new) {
            db!!.execSQL("DROP TABLE IF EXISTS $TABLE_NAME")
            onCreate(db)
        }
    }
}

My data only has "name" key


Solution

  • One way to execute only once the code that adds the data in the database is to use SharedPreferences.
    So inside onCreate() of MainActivity you check SharedPreferences if a certain Boolean value exists and it is true.
    If it does not exist then you add the data to the database and then set the Boolean value to true in SharedPreferences.
    If it exists nothing will happen because this is not the 1st time the app was ran.

    val sp: SharedPreferences = getSharedPreferences("MyAppPreferences", MODE_PRIVATE)
    if (!sp.getBoolean("First", false)) {
        <your code here>
        val ed = sp.edit()
        ed.putBoolean("First", true)
        ed.apply()
    }
    

    Replace the placeholder <your code here> with your code that adds the data to the database.