Android:关闭SQLite数据库

rya*_*dlf 6 sqlite android

对于关闭与sqlite数据库的连接,这更像是"我这样做是最好的方式"这样的问题.我一直在做的是在onpause和ondestroy方法中关闭我的视图活动中的数据库.当用户导航回活动时,我在onresume方法上重新查询数据库.这是一段代码:

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 queryDataBase() {
    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();
}
Run Code Online (Sandbox Code Playgroud)

当然,这不是整个活动,而只是处理sqlite数据库的部分.我是以整洁的方式做这件事还是我应该遵循更好的做法?

Ahm*_*gle 6

onDestroy 可能是放置任何IO连接的处理方法的最佳阶段.

另一种方法是使用try { query() } finally { db.close(); }模式 - 这也是有意义的,因此数据库仅在查询期间激活.

在Java 7中,有一种新的语法糖try (db = open database();) { execute queries(); }在执行查询完成后自动关闭数据库.但是Java 7尚未在Android设备上提供.