2011-07-15 119 views
6

这是关于关闭与sqlite数据库的连接的一种“我正在做这个最好的方式”类问题。我一直在做的是在onpause和ondestroy方法中的视图活动中关闭数据库。当用户导航回到我在onresume方法中查询数据库的活动时。下面是一段代码:Android:关闭SQLite数据库

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(); 
} 

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

回答

6

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

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

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

+0

我喜欢尝试/最后的想法。我得玩一玩,谢谢。 – ryandlf