How to add initial data for DB using GreenDao in android?

2.8k views Asked by At

I have been this answer for insert initial data in native mode

How to add initial data to SQLite database?

How can I get the same result using Green dao?

this is my Application class

public class App extends Application{


    @Override
    public void onCreate() {

        super.onCreate();
        DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(this,"Images-bd",null);
        SQLiteDatabase db = helper.getWritableDatabase();
        DaoMaster daoMaster = new DaoMaster(db);
        DaoSession daoSession = daoMaster.newSession();



    }

}
1

There are 1 answers

2
Allan Pereira On BEST ANSWER

You can create a class that extends DaoMaster and run your queries inside onCreate method:

public class CustomDaoMaster extends DaoMaster {
    public CustomDaoMaster(SQLiteDatabase db) {
        super(db);
    }

    public static class OpenHelper extends DaoMaster.OpenHelper {
        public OpenHelper(Context context, String name, SQLiteDatabase.CursorFactory factory) {
            super(context, name, factory);
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            super.onCreate(db);
            db.execSQL("INSERT INTO myTable VALUES('foo')");
            db.execSQL("INSERT INTO myTable VALUES('bar')");
        }
    }
}

So, in your Application class, you will use a instance of this class:

public class App extends Application {

    @Override
    public void onCreate() {
        super.onCreate();
        CustomDaoMaster.OpenHelper helper = new CustomDaoMaster.OpenHelper(this, "Images-bd", null);
        SQLiteDatabase db = helper.getWritableDatabase();
        CustomDaoMaster daoMaster = new CustomDaoMaster(db);
        DaoSession daoSession = daoMaster.newSession();
    }
}