-1

I want to create a SQLite database.
So I followed a tutorial and I have these two lines in my MainActivity that create the database.

LugaresDB lugaresDB = new LugaresDB(getApplicationContext());
SQLiteDatabase db = lugaresDB.getWritableDatabase();

My question: I expected just the first line to create the database, but it doesn't create it.
I have to add the second line. Why?

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115

2 Answers2

4

Because that's how the framework is implemented.

It's not possible to say exactly why it is implemented as such, but generally it is a good design idea to follow principles of single responsibility and least astonishment: a constructor is only responsible for object instance initialization. Any other actions such as actually opening the database with file I/O are undesirable side effects. These other actions are better modelled as methods with verb in their name.

laalto
  • 150,114
  • 66
  • 286
  • 303
0

Because that is the way the class is implemented. Your LugaresDB seems to be a subclass of SQLiteOpenHelper. The first line creates a helper object of class SQLiteOpenHelper which can be used to create either a read-only or writable instance of SQLiteDatabase, which is what the second line does.

teukkam
  • 4,267
  • 1
  • 26
  • 35