Get DaoSession in library project

0

Good morning Greetings to all, I am currently using learning to use greendao 3, I have read several tutorials and in all examples use greendao within an app, instead I am implementing it in a library project, my question is how to get the DaoSesssion in a library project, because to do it in the examples they do the following:

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

and in a library I can not use the getApplication function.

Thanks in advance for your answers.

    
asked by Roberto Fernandez 18.05.2017 в 18:33
source

1 answer

1

my solution, although not really if it is very good, was not dependent 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. therefore I decided to create a class with the singleton pattern and from there call when necessary to DaoSession. I'll leave the code for you if it's useful, or if you 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 is the way to use it:

DaoSession daoSession = DaoHelper.getInstance(context).getDaoSession();
    
answered by 19.05.2017 / 00:21
source