codepleb
codepleb

Reputation: 10571

When is onCreate() called in a non-activity class?

I looked up different tutorials about databases and saw, that it was mostly the same approach. What I don't understand: As I know, onCreate() can ONLY be called automatically by the start of an activity (startActivity(new Intent(this)). But in the following example, the class that extends SQLiteOpenHelper is not an activity but includes the onCreate() method, that never get called manually. How does this work and especially WHEN is its startpoint? Will this be called when you call the constructor? I tried to look this up with logcat and I never got a message, that onCreate() has been called.

I have a class like this:

public class MySQLiteHelper extends SQLiteOpenHelper {

    // Database Version
    private static final int DATABASE_VERSION = 1;
    // Database Name
    private static final String DATABASE_NAME = "BookDB";

    public MySQLiteHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        // SQL statement to create book table
        String CREATE_BOOK_TABLE = "CREATE TABLE books ( " +
                "id INTEGER PRIMARY KEY AUTOINCREMENT, " +
                "title TEXT, "+
                "author TEXT )";

        // create books table
        db.execSQL(CREATE_BOOK_TABLE);
    }

And an external Activity, that handles this class:

public class MyActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my);

        MySQLiteHelper db = new MySQLiteHelper(this);


        // add Books
        db.addBook(new Book("Android Application Development Cookbook", "Wei Meng Lee"));
        db.addBook(new Book("Android Programming: The Big Nerd Ranch Guide", "Bill Phillips and Brian Hardy"));
        db.addBook(new Book("Learn Android App Development", "Wallace Jackson"));

        // get all books
        List<Book> list = db.getAllBooks();
    }
}

Upvotes: 1

Views: 1516

Answers (2)

Eduard B.
Eduard B.

Reputation: 6803

The fact that both of the classes have a function with the same name doesn't mean that they have something in common. onCreate in SQLiteOpenHelper is called when you ask for the database for the first time (with getReadeableDatabase() or getWritableDatabase())

Upvotes: 1

CommonsWare
CommonsWare

Reputation: 1007484

As I know, onCreate() can ONLY be called automatically by the start of an activity (startActivity(new Intent(this)).

There are a variety of places in Android where onCreate() methods appear, including Activity, Service, ContentProvider, and SQLiteOpenHelper.

How does this work

onCreate() of a SQLiteOpenHelper will be called in response to an getReadableDatabase() or getWriteableDatabase() call, if and only if the database does not already exist.

Upvotes: 2

Related Questions