Good day, sorry for my bad English I'm using google translate, I'm new using greendao, I've read many tutorials in interner and all show an example of how to run it inside an activity, ie get the DaoSession as well:
DaoSession daoSession = ((App) getApplication()).getDaoSession();
My question is, how do I get the DaoSession in a project library? Since I can not call the getApplication()
thanks for your help
my solution, although not really if it is very optimum, was not depend on Application, because an android app can only have an Application class declared in the manifest of the main app where the library is run. So I decided to create a class with the singleton pattern and from there call when necessary to DaoSession. I leave the code in case it serves them, or if they can improve it.
this is the class
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;
}
}
And this a way to use it
DaoSession daoSession = DaoHelper.getInstance(context).getDaoSession();