DaoException: Entity is detached from DAO context

Abdul Samad picture Abdul Samad · Sep 2, 2013 · Viewed 7k times · Source

I have two entities, User and Store. User has many Stores (1:M) relation. I've inserted some stores list into the store table by following code.

public void saveStoresToDatabase(Context context, ArrayList<Store> storeList) {

    DevOpenHelper helper = new DaoMaster.DevOpenHelper(context, "notes-db", null);
    SQLiteDatabase db = helper.getWritableDatabase();
    DaoMaster daoMaster = new DaoMaster(db);

    DaoSession daoSession = daoMaster.newSession();
    StoreDao storeDao = daoSession.getStoreDao();

    ArrayList <Store> list = SharedData.getInstance().getUser().getStoreList();

    for(int i = 0; i < storeList.size(); i++) {
        storeList.get(i).setUserIdForStore(SharedData.getInstance().getUser().getId());
    }
    storeDao.insertOrReplaceInTx(storeList);
    list.addAll(storeList);
    user.resetStoreList();

}

I am getting "entity is detached from DAO context" exception whenever I try call user.getStoreList(). The exception occurs at following code sniped as the daoSession is null.

public ArrayList<Store> getDMStoreListFromDatabase(Context context) {
    return SharedData.getInstance().getUser().getStoreList();
}

where SharedData is my singleton, having a user object:

private SharedData() {
    user = new User();
}

and I get the sharedData instance as follow:

public static synchronized SharedData getInstance() {
    if (sharedObject == null) {
        sharedObject = new SharedData();
    }
    return sharedObject;
}

Answer

AlexS picture AlexS · Sep 11, 2013

Objects representing database entries (like User) are only attached to a Database-session if they have been fetched from the database or inserted to the database before.

It looks like you don't load your user-object using greendao, but instead just create it with new.

You also seem not to store this user-object using the dao. Thus the user-object is not attached to the session.

On top of that you are also just setting the userid in each store. If you haven't inserted the user-object somewhere else this may also cause an error since the foreignkey-constraint may be broken (depending on how greendao handles this internally).

Try to add the user-object to the stores with setUser() instead of setUserIdForStore().

If this doesn't work try to store or load the user-object first using a UserDao.