This was a problem for me when I first started working with Android, as there are not many tutorials on the Internet that describe how to correctly allow access to your database throughout the application (do not ask me why). Here is an example code that shows three possible approaches.
Approach # 1: Subclassification of `Application`
If you know that your application will not be very complex (i.e. if you know that you will have only one subclass of Application ), then you can create a subclass of Application and expand your main activity of This. This ensures that one instance of the database runs throughout the application life cycle.
public class MainApplication extends Application { private static DataDbAdapter mDbHelper; @Override public void onCreate() { mDbHelper = new DataDbAdapter(this); mDbHelper.open(); } @Override public void onTerminate() { mDbHelper.close(); mDbHelper = null; } public static DataDbAdapter getDatabaseHelper() { return mDbHelper; } }
Approach # 2: there is `SQLiteOpenHelper` - a static data member
This is not a complete implementation, but it should give you a good idea on how to plan the DatabaseHelper class correctly. The static factory method ensures that at any time there is only one instance of DatabaseHelper.
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) { if (mInstance == null) { mInstance = new DatabaseHelper(ctx.getApplicationContext()); } return mInstance; } private DatabaseHelper(Context ctx) { super(context, DATABASE_NAME, null, DATABASE_VERSION); this.mCtx = ctx; } }
Approach # 3: SQLite Database Annotation Using ContentProvider
This is the approach I would suggest. Firstly, the new LoaderManager class is heavily dependent on ContentProviders, so if you want to implement Activity or Fragment LoaderManager.LoaderCallbacks<Cursor> (which I suggest you use, it's magic!), You will need to implement ContentProvider for your application. In addition, you do not need to worry about creating a Singleton database assistant with ContentProviders. Just call getContentResolver() from the Activity, and the system will take care of everything for you (in other words, there is no need to develop a Singleton template to prevent multiple instances from being created).
Hope this helps!
source share