我有两个实体,User
并且Store
. User
有很多Stores
(1:M) 关系。我通过以下代码将一些商店列表插入到商店表中。
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();
}
每当我尝试调用时,我都会收到“实体与 DAO 上下文分离”异常 user.getStoreList()
。异常发生在以下代码中,如下daoSession
所示null
。
public ArrayList<Store> getDMStoreListFromDatabase(Context context) {
return SharedData.getInstance().getUser().getStoreList();
}
我的单身人士在哪里SharedData
,有一个用户对象:
private SharedData() {
user = new User();
}
我得到的sharedData
实例如下:
public static synchronized SharedData getInstance() {
if (sharedObject == null) {
sharedObject = new SharedData();
}
return sharedObject;
}