To implement database access in my application I followed Lars Vogel tutorial, but I’m very confused about a couple of things…
The TodoDbAdapter class has the following constructor and open method:
public TodoDbAdapter(Context context) {
this.context = context;
}
public TodoDbAdapter open() throws SQLException {
dbHelper = new TodoDatabaseHelper(context);
database = dbHelper.getWritableDatabase();
return this;
}
And then this adapter should be initialized like this:
dbAdapter = new TodoDbAdapter(this);
dbAdapter.open();
1) The getWriteableDatabase method is the one responsible by throwing a possible SQLException. Why do we need to rethrow in our open method? Is there a reason for this?
2) What’s the point of the whole constructor/open pair? Why not initialize dbHelper and get a database ready for writing in the constructor?
3) Why do we return the instance of the object in the open method with return this? If the open method code were to be moved to the constructor, we no would no longer need to return this, it would be implicit, right? What am I missing here?
It’s a matter of style to explicitly declare runtime exception like this to highlight that
open()might fail. If you don’t want to handle it, remove the throws clause.This allows you to create the instance (fast operation) without being forced to do the probably slow operation (disk IO, etc.) of opening the database; most of the time this won’t matter because you’ll do both in one go as in your code snippet. Also, this keeps the constructor exception-free which some people prefer.
If it were moved into the constructor, then yes the
return thiswould be implicit. As the usual way to use a DB helper class in Android is to create and open it in one go,open()just does some little builder pattern so you can goTodoDbAdapter helper = new TodoDbAdapter(this).open();for the most common use case.To sum up: These three points of yours are mainly about style, there’s little functional reason I can think of and definitely other ways to do it that are correct.