I know that SQLiteDatabase doesn't have any public constructor and I cannot create its object directly.
But then how is SQLiteOpenHelper able to return SQLiteDatabase reference using getReadableDatabase() or getWritableDatabase()?
I know that SQLiteDatabase doesn't have any public constructor and I cannot create its object directly.
But then how is SQLiteOpenHelper able to return SQLiteDatabase reference using getReadableDatabase() or getWritableDatabase()?
Just because the constructor isn't public/visible doesn't mean it doesn't exist!
SQLiteOpenHelper
uses SQLiteDatabase
's static constructor openDatabase
to create a new database instance. It is public and has not been hidden so, although it is probably not a good idea, you could call it, directly, yourself.
According to the doc you would use it like this:
SQLiteDatabase db = SQLiteDatabase.openDatabase(path, null);
The first argument is a String giving the full path name for the new db. The second is the cursor factory. Passing null for the second arg will get you the default factory.
Using the SQLiteOpenHelper
guarantees that the db is correctly created and correctly initialized. It also properly caches db instances, so that they aren't recreated every time you need them. It is probably better to use it.
Try this:
Class Cdb.java:
public class Cdb extends SQLiteOpenHelper {
private static final String DB_NAME = "db_name.db";
public static final int DB_VERSION = 1;
Cdb(Context context) {
super(context.getApplicationContext(), DB_NAME, null, DB_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion){
// Upgrade here
}
@Override
public void onOpen(SQLiteDatabase db) {
super.onOpen(db);
}
and then you may access the database as follows:
Cdb openHelper = new Cdb(this);
SQLiteDatabase db = openHelper.getReadableDatabase();