开发者

Android: Closing SQLite Database

This is more of a "Am I doing this the best way" kind of question in regards to closing the connection to an sqlite database. What i've been doing is closing the database within my view activity in the onpause and ondestroy methods. When the user navigates back to the activity I requery the database on the onresume method. Here is a snippet of code:

private void setupView() {

    newRecipeButton = (Button)findViewById(R.id.NewRecipeButton);
    newRecipeButton.setOnClickListener(addNewRecipe);

    list = (ListView)findViewById(R.id.RecipeList);
    dbHelper = new DataBaseHelper(this);
    setupDataBase();
    database = dbHelper.getMyDataBase();
    queryDataBase();
    list.setEmptyView(findViewById(R.id.EmptyList));
    registerForContextMenu(list);
}

private void qu开发者_开发知识库eryDataBase() {
    data = database.query("recipes", fields, null, null, null, null, null);
    dataSource = new DataBaseAdapter(this, R.layout.recipe_list_item, data, fields, new int[] {R.id.RecipeName, R.id.RecipeStyle});
    list.setAdapter(dataSource);
}

private void setupDataBase() {
    //Create the database if this is the first run.
    try{
        dbHelper.createDataBase();
    } catch(IOException e){
        throw new Error("Unable to Create Database");
    }

    //Otherwise open the database.
    try{
        dbHelper.openDataBase();
    }catch (SQLiteException e){
        throw e;
    }
}

@Override
protected void onResume(){
    super.onResume();
    setupView();
}

@Override
protected void onDestroy() {
    super.onDestroy();
    dbHelper.close();
}

Of course this isn't the entire activity but merely the parts that deal with the sqlite database. So am I doing this in a tidy manner or is there a better practice I should be following?


onDestroy is probably the best phase to place disposal method of any IO connection.

Another approach is using try { query() } finally { db.close(); } pattern – which also makes sense so that database is only activated during your query.

In Java 7, there is a new syntactic sugar try (db = open database();) { execute queries(); } that closes database automatically after executing queries finishes. However Java 7 is not available on Android devices yet.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜