Yes, you can write a custom bootloader in which you must manually report database changes when saving data to the database. For this purpose, you can use broadcast receivers, a green robot event bus, etc. See code below
A custom message loader class to load data whenever it receives notification via eventbus. MessageListLoader.java
public class MessageListLoader extends AsyncTaskLoader<List<Message>> { private List<Message> mMessages; private long mGroupId; private Context mContext; public MessageListLoader(Context context, long groupId) { super(context); mGroupId = groupId; } private IMobileService getMobileService() { return MobileServiceImpl.getInstance(mContext); } @Override public List<Message> loadInBackground() { return getMobileService().getMessagesByGroupId(mGroupId); } @Override public void deliverResult(List<Message> newMessageList) { if (isReset()) { mMessages = null; return; } List<Message> oldMessageList = mMessages; mMessages = newMessageList; if (isStarted()) { super.deliverResult(newMessageList); }
The mobile service class is used, which provides all the services associated with the database.
MobileServiceImpl.java
public class MobileServiceImpl implements IMobileService { private static final String TAG = "MobileServiceImpl"; private static final String DATABASE_NAME = "demo.db"; private static IMobileService instance = null; private DaoSession mDaoSession; private MobileServiceImpl(Context context) { DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(context, DATABASE_NAME, null); SQLiteDatabase db = helper.getWritableDatabase(); DaoMaster daoMaster = new DaoMaster(db); mDaoSession = daoMaster.newSession(); } public static IMobileService getInstance(Context context) { if (instance == null) { instance = new MobileServiceImpl(context); } return instance; } private MessageDao getMessageDao() { return mDaoSession.getMessageDao(); } @Override public long saveMessage(Message message, boolean notifyUi) { long id = getMessageDao().insert(message); if (notifyUi) EventBus.getDefault().post(new NewMessageEvent(id)); return id; } @Override public List<Message> getMessagesByGroupId(long groupId) { return getMessageDao() .queryBuilder() .where(MessageDao.Properties.GroupId.eq(groupId)) .orderDesc(MessageDao.Properties.Id).list(); } @Override public Message getMessageById(long messageId) { return getMessageDao().load(messageId); } }
Download sample project here
source share