如何在Android中使用GreenDao为DB添加初始数据?

时间:2016-02-08 16:50:10

标签: java android sqlite greendao greendao-generator

我一直是以纯模式插入初始数据的答案

How to add initial data to SQLite database?

如何使用Green dao获得相同的结果?

这是我的Application类

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 个答案:

答案 0 :(得分:4)

您可以创建一个扩展DaoMaster的类,并在onCreate方法中运行您的查询:

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')");
        }
    }
}

因此,在您的Application课程中,您将使用此课程的一个实例:

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