简体   繁体   中英

How can SQLiteOpenHelper return SQLiteDatabase?

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM