如何在项目库中获取DaoSession?

时间:2017-05-18 15:44:36

标签: greendao greendao3

美好的一天,抱歉我的英语不好我使用谷歌翻译,我是使用greendao的新手,我已经阅读了很多关于interner的教程,并且都展示了如何在里面运行它的例子一项活动,即获得DaoSession:

DaoSession daoSession =((App)getApplication())。getDaoSession();

我的问题是,如何在项目库中获取DaoSession?因为我无法拨打getApplication()

感谢您的帮助

1 个答案:

答案 0 :(得分:0)

我的解决方案,虽然不是真的非常优化,但不依赖于Application,因为Android应用程序只能在运行库的主应用程序的清单中声明一个Application类。所以我决定创建一个带有单例模式的类,并在必要时调用DaoSession。我保留代码,以防它们为它们服务,或者如果它们可以改进它。

这是班级

public class DaoHelper {

private static volatile DaoHelper daoInstance;
private DaoSession daoSession;

private DaoHelper(Context context){
    //Prevent form the reflection api
    if(daoInstance!=null){
        throw new RuntimeException("Use getInstance() method to get the single instance of this class.");
    }else{
        CustomDaoMaster.OpenHelper helper = new CustomDaoMaster.OpenHelper(context,
                "db",null);
        SQLiteDatabase db = helper.getWritableDatabase();
        CustomDaoMaster daoMaster = new CustomDaoMaster(db);
        daoSession = daoMaster.newSession();
    }
}

public static DaoHelper getInstance(Context context){
    //Double check locking pattern
    if(daoInstance==null){
        synchronized (DaoHelper.class){//Check for the second time.
            //if there is no instance available... create new one
            if(daoInstance==null)daoInstance = new DaoHelper(context);
        }
    }

    return daoInstance;
}

public DaoSession getDaoSession(){
    return daoSession;
}

}

这是一种使用它的方法

DaoSession daoSession = DaoHelper.getInstance(context).getDaoSession();