It is rather a question of "I do it best" in relation to closing the connection to the sqlite database. What I did was close the database in my view activity in the onpause and ondestroy methods. When the user goes into activity, I query the database using the onresume method. Here is the code snippet:
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(); }
Of course, this is not all activity, but simply parts that relate to the sqlite database. So am I doing this carefully or is there a best practice that I should follow?
source share