SQLiteOpenHelper "onCreate" is not called? (the DB does not exist)

znat picture znat · Apr 13, 2012 · Viewed 7.2k times · Source

From a fragment I instantiate this way

fmdata = new FileManagerData(getActivity());

the following class. I don't understand why onCreate() is not called and my database does not get created.

public class FileManagerData {
public static final String TAG = FileManagerData.class.getSimpleName();;


Context context;
DBHelper dbHelper;

public FileManagerData (Context context){
    this.context = context;
    dbHelper = new DBHelper();
}

private class DBHelper extends SQLiteOpenHelper{

    private static final String DB_NAME = "filename.db";
    private static final String DB_SQL = "filename.sql";
    private static final int DB_VERSION = 1; // internal number

    public DBHelper() {
        super(context, DB_NAME, null, DB_VERSION);  
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
            // this is NEVER called and my DB does not exist yet
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }   
}

EDIT: The trick is that the database has to be used (to read or write) so onCreate() get called.

Answer

marwinXXII picture marwinXXII · Apr 13, 2012

The onCreate method will be called after first access to the DB. Make a query to the DB and onCreate will be invoked.