SQLiteOpenHelper - how is the database created?
Asked Answered
R

7

11

I'm making a database application, and my program works and I've understood most of the tutorial I've been following. However, one aspect remains unclear to me.

There is an inner class of MyDBHelper extending SQLiteOpenHelper. Outer variables include the SQLiteDatabase called d. The code for the MyDBHelper is:

private static class MyDBHelper extends SQLiteOpenHelper {
        MyDBHelper(Context c) {
            super(c, DB_NAME, null, DB_VERSION);
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            try {
                db.execSQL(DATABASE_CREATE);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVers, int newVers) {
            Log.w(TAG, "Upgrading database from version " + oldVers + " to " + newVers + ", which will destroy all old data.");
            db.execSQL("DROP TABLE IF EXISTS GM");
            onCreate(db);
        }
    }

My question is how does this actually create the initial database. It occurs in the onCreate() method, but as far as I can see, this is never called. I understand that it is called when the database is created for the first time, but where? And furthermore, how is it passed a SQLiteDatabase db? I haven't passed any database to the method. And how is my SQLiteDatabase db variable from the outer class set to the created database? Could someone talk me through this like an idiot?

Ryder answered 3/9, 2012 at 20:23 Comment(0)
O
8

onCreate() and onUpgrade() methods are really called the first time when Db is created. In facts, it's checked in getReadableDatabase() or getWritebleDatabase() methods of SQLiteOpenHelper. It will check if the DB already exist on the data directory and what is it's version. According to this it will either call onCreate(), or onUpgrade(). Or nothing, if db file exist and of correct version.

You can search your code for executing myDBHelper.getReadable(Writable)Database(). That is the time when this check will be performed.

Please let me know if more details are needed. Good luck

Obau answered 3/9, 2012 at 20:33 Comment(0)
G
4

Keep in mind that you are extending SQLiteOpenHelper, all of the magic happens in this super class, specifically the database is initially created (or just re-opened) when you call either getReadableDatabase() or getWritableDatabase(). These two methods:

  • Define the SQLiteDatabase db variable (and control passing db to your callback methods)
  • Initialize db by calling your onCreate(db) method or opening the existing database
  • Check the version number and call your onUpgrade(db) or onDowngrade(db) if necessary

They also call a few more callback methods like onConfigure(db), onOpen(db), etc. (Read more about these methods.) If it will help, you can read through the source code yourself to understand the structure of how and when all of this happens.

Greenockite answered 3/9, 2012 at 20:33 Comment(0)
B
1

The onCreate() method is not a constructor for this class. onCreate is called when you create the DB.

Here PeopleDB extends SQLiteOpenHelper. This code is from a different class and onCreate is called when getWritableDatabase() or getReadableDatabase(), or anything of the sort is called

  PeopleDB db = null; //onCreate NOT called here
  db=new PeopleDB(getContext());
  db.getWritableDatabase();  //onCreate is called here!

Hope that helps.

Blaise answered 3/9, 2012 at 20:40 Comment(0)
M
1

See our database is created in the openhelper's constructor itself not in the overridden onCreate method. Inside onCreate method we are firing a query for creating a table in the database which is created in open helper's constructor to insert the data not creating the database.

One more thing is SQLiteDatabase object is not instantiated in SQLiteOpenHelper class. It is instantiated in the class where you want to use the database to perform db operations and there you need to write a function like this to intialise or open your database to get ready for insertion.

SQLiteDatabase database;

YourOpenHelper yourOpenHelper=new YourOpenHelper(); //to creating database using openhelper and automatically call onCreate to make a table in that

    public void open() throws SQLException {
            database = profiloHelper.getWritableDatabase();
        }

Here is code you have to write for any operation in database like insertion deletion anything, you just have to change the QUERY

SQLiteStatement insert_stmt = null;

        try {
            insert_stmt = database.compileStatement(YOUR_QUERY);

            insert_stmt.bindString(1,   field1);
            insert_stmt.bindString(2,   field2);
            insert_stmt.executeInsert();
        }
        finally {
            if (insert_stmt != null) insert_stmt.close();
        }
Matins answered 3/9, 2012 at 20:48 Comment(0)
D
0

Probably, in getReadableDatabase() or getWriteableDatabase() when they are called for the first time


Desimone answered 3/9, 2012 at 20:33 Comment(0)
R
0

You create a subclass implementing onCreate(SQLiteDatabase), onUpgrade(SQLiteDatabase, int, int) and optionally onOpen(SQLiteDatabase), and this class takes care of opening the database if it exists, creating it if it does not, and upgrading it as necessary. (Android Developer Website)

Rosannrosanna answered 2/5, 2013 at 19:40 Comment(0)
A
0

The class SQLiteOpenHelper is called "Helper" for good reason. It saves us app writers considerable effort.

The first time that you call getWritableDatabase (or getReadableDatabase) for your implementation of SQLiteOpenHelper, your super statement in your constructor passes the current Context and the database NAME that you prefer to the superclass constructor for SQLiteOpenHelper.

The superclass constructor then sets up initial space for your SQLiteDatabase and assigns it the name that you passed through super.

When finished, the superclass constructor calls onCreate and passes the named SQLiteDatabase that it created through onCreate's only parameter. Since onCreate only gets called this one time, it's a very good place to call execSQL to define the structure of your database.

Subsequent executions of getReadableDatabase (or getWritableDatabase) merely open the database for you and never again call onCreate. (When the superclass constructor notes that super has sent a different version number, onUpgrade is calle.)

Understanding the way SQLiteOpenHelper creates a database without obvious code and how the heck onCreate gets passed an argument "out of the blue" was a real chore for me. Now I can't believe it could have ever been hard.

Arezzo answered 25/9, 2017 at 3:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.