Android: closing SQLite database

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?

+6
source share
1 answer

onDestroy is probably the best phase to host the removal method of any I / O.

Another approach uses the template try { query() } finally { db.close(); } try { query() } finally { db.close(); } , which also makes sense, so that the database is activated only during your request.

Java 7 introduced a new syntax sugar try (db = open database();) { execute queries(); } try (db = open database();) { execute queries(); } , which automatically closes the database after query completion. However, Java 7 is not yet available on Android devices.

+6
source

Source: https://habr.com/ru/post/892810/


All Articles