2011-07-15 175 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