Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: Closing SQLite Database

Tags:

android

sqlite

This is more of a "Am I doing this the best way" kind of question in regards to closing the connection to an sqlite database. What i've been doing is closing the database within my view activity in the onpause and ondestroy methods. When the user navigates back to the activity I requery the database on the onresume method. Here is a snippet of code:

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 isn't the entire activity but merely the parts that deal with the sqlite database. So am I doing this in a tidy manner or is there a better practice I should be following?

like image 421
ryandlf Avatar asked Jul 15 '11 06:07

ryandlf


1 Answers

onDestroy is probably the best phase to place disposal method of any IO connection.

Another approach is using try { query() } finally { db.close(); } pattern – which also makes sense so that database is only activated during your query.

In Java 7, there is a new syntactic sugar try (db = open database();) { execute queries(); } that closes database automatically after executing queries finishes. However Java 7 is not available on Android devices yet.

like image 182
ahmet alp balkan Avatar answered Oct 23 '22 05:10

ahmet alp balkan