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數據庫的部分。那麼,我是以一種整潔的方式來做這件事,還是我應該遵循一個更好的做法?
我喜歡嘗試/最後的想法。我得玩一玩,謝謝。 – ryandlf