Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Database global instance

So I want to have one database instance for all application activities. I found the following code:

public class MyApplication extends Application {

    private static SQLiteDatabase mDB = null;

    @Override
    public void onCreate() {
        super.onCreate();
    DataBaseOpenHelper m_OpenHelper = new DataBaseOpenHelper( this );
    mDB = m_OpenHelper.getWritableDatabase();
    }

    public static SQLiteDatabase getDB() {
        return mDB;
    }
}

I don`t understand when I can close SQLiteDatabase instance.

like image 557
dimika Avatar asked Sep 01 '11 22:09

dimika


People also ask

What is global database in AWS?

The Amazon Aurora Global Database enables a single database cluster to span multiple AWS Regions by asynchronously replicating your data within subsecond timing. This provides fast, low-latency local reads in each Region. It also enables disaster recovery from Region-wide outages using multi-Region writer failover.

What is global DB?

Global Database provides company data across 195 countries worldwide. It is by far the largest business directory platform available that allows access to leading companies and their key contacts. Global Database. www.globaldatabase.com. 2015.

What is the difference between AWS RDS and Aurora?

RDS allows you to provision up to 5 replicas, and the process of replication is slower compared to Aurora. Aurora allows you to provision up to 15 replicas, and the replication is done in milliseconds. Aurora scales faster because it can add new read replicas quickly.


2 Answers

This was an issue for me when I first started out with Android, as there aren't many tutorials on the web that describe how to correctly allow access to your database across the entire application (don't ask me why). Here's some sample code that exhibits three possible approaches.

Approach #1: subclassing `Application`

If you know your application won't be very complicated (i.e. if you know you'll only end up having one subclass of Application), then you can create a subclass of Application and have your main Activity extend it. This ensures that one instance of the database is running throughout the Application's entire life cycle.

public class MainApplication extends Application {

    /**
     * see NotePad tutorial for an example implementation of DataDbAdapter
     */
    private static DataDbAdapter mDbHelper;

    /**
     * create the database helper when the application is launched 
     */
    @Override
    public void onCreate() {
        mDbHelper = new DataDbAdapter(this);
        mDbHelper.open();
    }

    /** 
     * close the database helper when the application terminates.
     */
    @Override
    public void onTerminate() {
        mDbHelper.close();
        mDbHelper = null;
    }

    public static DataDbAdapter getDatabaseHelper() {
        return mDbHelper;
    }
}

Approach #2: have `SQLiteOpenHelper` be a static data member

This isn't the complete implementation, but it should give you a good idea on how to go about designing the DatabaseHelper class correctly. The static factory method ensures that there exists only one DatabaseHelper instance at any time.

/**
 * create custom DatabaseHelper class that extends SQLiteOpenHelper
 */
public class DatabaseHelper extends SQLiteOpenHelper { 
    private static DatabaseHelper mInstance = null;

    private static final String DATABASE_NAME = "databaseName";
    private static final String DATABASE_TABLE = "tableName";
    private static final int DATABASE_VERSION = 1;

    private Context mCxt;

    public static DatabaseHelper getInstance(Context ctx) {
        /** 
         * use the application context as suggested by CommonsWare.
         * this will ensure that you dont accidentally leak an Activitys
         * context (see this article for more information: 
         * http://developer.android.com/resources/articles/avoiding-memory-leaks.html)
         */
        if (mInstance == null) {
            mInstance = new DatabaseHelper(ctx.getApplicationContext());
        }
        return mInstance;
    }

    /**
     * constructor should be private to prevent direct instantiation.
     * make call to static factory method "getInstance()" instead.
     */
    private DatabaseHelper(Context ctx) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
        this.mCtx = ctx;
    }
}

Approach #3: abstract the SQLite database with a `ContentProvider`

This is the approach I would suggest. For one, the new LoaderManager class relies heavily on ContentProviders, so if you want an Activity or Fragment to implement LoaderManager.LoaderCallbacks<Cursor> (which I suggest you take advantage of, it is magical!), you'll need to implement a ContentProvider for your application. Further, you don't need to worry about making a Singleton database helper with ContentProviders. Simply call getContentResolver() from the Activity and the system will take care of everything for you (in other words, there is no need for designing a Singleton pattern to prevent multiple instances from being created).

Hope that helps!

like image 138
Alex Lockwood Avatar answered Sep 22 '22 07:09

Alex Lockwood


You dont really need to close it. It will be automatically closed when your process dies. Instead of using the Application object, you can just make your DB helper object a singleton for easier access. BTW, getWritableDatabase() and getReadableDatabase() are not that different. The only difference is that getReadableDatabase() might work if you are out of space, while the other will throw an exception.

like image 31
Nikolay Elenkov Avatar answered Sep 21 '22 07:09

Nikolay Elenkov