Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 319
znat Avatar asked Dec 09 '22 01:12

znat


1 Answers

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

like image 185
marwinXXII Avatar answered Jan 13 '23 02:01

marwinXXII