これは、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データベースを処理する部分です。だから私はこれを整然としたやり方でやっているのか、それとも後に続くべきであるより良い練習があるのだろうか?
私はtry/finallyアイデアが好きです。私はそれで周り遊ぶ必要があります、ありがとう。 – ryandlf