angel February 2016

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

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



    }

}

Answers


Allan Pereira February 2016

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 DevOpenHelper extends DaoMaster.DevOpenHelper {
        public DevOpenHelper(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.DevOpenHelper helper = new CustomDaoMaster.DevOpenHelper(this, "Images-bd", null);
        SQLiteDatabase db = helper.getWritableDatabase();
        CustomDaoMaster daoMaster = new CustomDaoMaster(db);
        DaoSession daoSession = daoMaster.newSession();
    }
}

Post Status

Asked in February 2016
Viewed 2,390 times
Voted 12
Answered 1 times

Search




Leave an answer