0

I'm practicing android, I was able to insert using db.insert() without the use of getWritableDatabase() why is that? I thought we need db = getWritableDatabase(); before we can insert to the database

private SQLiteDatabase db;

@Override
public void onCreate(SQLiteDatabase db) {
    this.db = db;

    //some table creation
    db.execSQL(TABLE);
    fillQuestionsTable();


}

  private void insertQuestion(Question question){
    ContentValues cv = new ContentValues();
    //some code
    db.insert(QuestionsTable.TABLE_NAME, null, cv);

}

I thought it should be like this?

  private void insertQuestion(Question question){
     db = getWritableDatabase();
     ContentValues cv = new ContentValues();
     //some code
     db.insert(QuestionsTable.TABLE_NAME, null, cv);

}

here's my implementation:

 private void fillQuestionsTable(){

    Question q1 = new Question("Programming, Easy: A is correct", "A", "B", "C",
            1, Question.DIFFICULTY_EASY, Category.PROGRAMMING);
    insertQuestion(q1);
    
}

1 Answers1

0

your code works, because you are storing reference to db object in onCreate and then re-using this reference further. that should work in most of common cases, but getWritableDatabase() and getReadableDatabase() methods are there for a reason - you should use them in your insert/update/remove methods just like you posted. For safer, more reliable access in future app releases when there may/probably will be more code, more tables and more complicated lifecycle of app. and get rid of private SQLiteDatabase db; declaration on top of your SQLiteOpenHelper, use only locally fetched (with above methods) database object

snachmsm
  • 17,866
  • 3
  • 32
  • 74
  • Why should I get rid of `private SQLiteDatabase db;` isn't much more convienient to just rely on it just like I did in the first block of code above instead of using `getWritableDatabase()` or `getReadableDatabase()` in every CRUD method which adds one more line to our code? – James Gosling Apr 20 '22 at 15:26
  • I know my code is not timely anymore, there are content providers and android architecture components that I need to implement but I just wanna know the basic stuff first. – James Gosling Apr 20 '22 at 15:26
  • check out [THIS](https://stackoverflow.com/questions/47908444/why-is-getwritabledatabase-necessary-to-create-a-sqlite-database/47908684) answer – snachmsm Apr 20 '22 at 18:51