DaoException: entity excluded from DAO context

I have two objects, User and Store . User has many relationships Stores (1: M). I entered the list of stores in the storage table by running the 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 get an β€œentity from exception from DAO context” exception whenever I try to call user.getStoreList() . An exception occurs with the following code that was discarded because daoSession is null .

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

where SharedData is my singleton having a custom object:

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

and I get an instance of SharedData as follows:

 public static synchronized SharedData getInstance() { if (sharedObject == null) { sharedObject = new SharedData(); } return sharedObject; } 
+6
source share
1 answer

Objects representing database records (for example, User ) are attached only to the database session if they were retrieved from the database or inserted into the database earlier.

It looks like you are not loading your custom object using greendao, but instead just create it using new .

You also do not save this custom object with dao. Thus, the user object is not attached to the session.

In addition, you also simply set the user ID in each repository. If you have not yet inserted the user object in another place, this may also cause an error, as the foreign key constraint may be violated (depending on how greendao handles this internally).

Try adding a custom object to stores using setUser() instead of setUserIdForStore() .

If this does not work, try saving or loading the user object first using UserDao .

+9
source

Source: https://habr.com/ru/post/952995/


All Articles