Skip to content Skip to sidebar Skip to footer

When Close The Bbdd And When Close The Cursor?

anyone can teach me when i should to close a sqlite open bbdd and a cursor? I have this class public class DataBaseHelper { Context context; private static final Strin

Solution 1:

I don't know precisely, but for my opinion I think that you have to open database in onResume method of your activity and close it onPause. As for Cursors you should close them after you do not need them. For instance, if your database helper class returns cursor as a result of query then you should close it when you process all rows of the cursor.

I advice you to consider Notepad example. There are some very good tips how to work with databases in Android.

UPDATE: Here is an example how I usually populate my list in an activity:

publicclassAcWordsextendsActivity {
    /** Called when the activity is first created. */DbWordsAdapter dbWordsAdapter;
    ListView vw;

    @OverridepublicvoidonCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.ac_words);

        vw = (ListView) findViewById(R.id.ac_words_lv_words);

        dbWordsAdapter = newDbWordsAdapter(this);
        dbWordsAdapter.open();
    }

    @OverrideprotectedvoidonResume() {
        // TODO Auto-generated method stubsuper.onResume();
        SimpleCursorAdapter adtWord = newSimpleCursorAdapter(this, R.layout.ac_words_vw_wordrow,
                dbWordsAdapter.getWordsOrderedByAlph(),
                newString[] { DbWordsAdapter.C_WORD, DbWordsAdapter.C_EXPLANATION },
                new int[] { R.id.ac_words_vw_wordrow_tv_word, R.id.ac_words_vw_wordrow_tv_explanation });

        vw.setAdapter(adtWord);
    }


    @OverrideprotectedvoidonPause() {
        // TODO Auto-generated method stubsuper.onPause();
        dbWordsAdapter.close();
    }

}

And this is my helper class:

publicclassDbWordsAdapter {

    privatestaticfinalStringTAG= DbWordsHelper.class.getSimpleName();
    privatestaticfinalStringDATE_FORMAT="yyyy-MM-dd HH:mm:ss";

    privatestatic DbWordsHelper dbWordsHelper; 
    private Context context;
    private SQLiteDatabase mDb;

    // database constantsprivatestaticfinalStringDB_NAME="words.db";
    privatestaticfinalintDB_VERSION=1;
    privatestaticfinalStringTABLE_WORDS="words";

    // database columns namespublicstaticfinalStringC_ID= BaseColumns._ID;
    publicstaticfinalStringC_WORD="word";
    publicstaticfinalStringC_EXPLANATION="explanation";
    publicstaticfinalStringC_CREATION_DATE="creation_date";

    //Sql StatementsstaticfinalStringCREATE_TABLE_WORDS="create table " + TABLE_WORDS
            + "(" + C_ID + " integer primary key autoincrement, " + C_WORD
            + " text not null, " + C_EXPLANATION + " text, "
            + C_CREATION_DATE + " date not null)";
    staticfinalStringDROP_TABLE_WORDS="drop table if exists "
            + TABLE_WORDS;      
    staticfinal String[] ALL_COLUMNS = { C_ID, C_WORD, C_EXPLANATION,
            C_CREATION_DATE };
    staticfinalStringORDER_BY_DATE= C_CREATION_DATE + " desc";
    staticfinalStringORDER_BY_ALPH= C_WORD + " asc";
    staticfinalStringORDER_BY_RANDOM="random() limit 1";


    /*
     * Inner class that manages database creation and management
     */privatestaticclassDbWordsHelperextendsSQLiteOpenHelper {

        privateDbWordsHelper(Context context) {
            super(context, DB_NAME, null, DB_VERSION);
        }

        @OverridepublicvoidonCreate(SQLiteDatabase db) {
            Log.d(TAG, "SqlCreate Statement: "
                    + CREATE_TABLE_WORDS);

            try {
                db.execSQL(CREATE_TABLE_WORDS);
            } catch (SQLException e) {
                Log.e(TAG, "Error while creating database" + TABLE_WORDS, e);
            }

        }

        @OverridepublicvoidonUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

            // Here in the future should be method that change the schema of the// database. Now we just deletetry {
                db.execSQL(DROP_TABLE_WORDS);
            } catch (SQLException e) {
                Log.e(TAG, "Error while updating database" + TABLE_WORDS, e);
            }

            onCreate(db);

        }
    }

    publicDbWordsAdapter(Context context) {
        this.context = context;
    }

    public DbWordsAdapter open() {
        if (dbWordsHelper == null) {
            dbWordsHelper = newDbWordsHelper(context);
        }
        mDb = dbWordsHelper.getWritableDatabase();
        returnthis;
    }

    publicvoidclose() {
        dbWordsHelper.close();
        dbWordsHelper = null;
    }

    public Cursor getWordDetails(long rowId) {
        Log.d(TAG, "getWordDetails method");
        CursormCursor= mDb.query(TABLE_WORDS, ALL_COLUMNS, C_ID + "=?",
                newString[] { String.valueOf(rowId) }, null, null, null);
        return mCursor;
    }
}

You can use it as a template for your case.

Post a Comment for "When Close The Bbdd And When Close The Cursor?"