开发者

Confused about initialization of SQLite database in Android

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 开发者_JAVA技巧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?


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?

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.

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?

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.

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?

If it were moved into the constructor, then yes the return this would 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 go TodoDbAdapter 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜