How to convert local data to DataSource. Factory without using room,
Recently, I used the Android Architecture Components, a new framework released by google. It is very cool to use. I don't have to worry about data persistence, automatic refresh, and other lifecycle issues. However, I encountered a problem. This framework is very helpful, but if I use a few of them, I will encounter some problems. For example, I do not use the room SQL framework to convert my database dataDataSource. Factory. The following describes how to solve the problem:
View the room source code and find allData conversion related to DataSource. Factory is usedLimitOffsetDataSource class, so we only need to follow this class to implement our ownData Source. Factory can be converted.
Step 1
Create an inheritancePositionalDataSource abstract class. Because my local database framework uses DBFlow, I need to input several parameters that I need to monitor database changes:
Public abstract class LimitOffsetDataSource
Extends PositionalDataSource
{Private Class
MClass; private FlowContentObserver mContentObserver; private Where
MWhere; protected LimitOffsetDataSource (final Class
AClass, Context context, Where where) {mClass = aClass; mWhere = where; // listener Database Change mContentObserver = new FlowContentObserver (FlowManager. DEFAULT_AUTHORITY); mContentObserver. registerForContentChanges (context, mClass); mContentObserver. addContentChangeListener (new FlowContentObserver. contentChangeListener () {@ Override public void onModelStateChanged (@ Nullable Class
Table, BaseModel. Action action, @ NonNull SQLOperator [] primaryKeyValues) {invalidate () ;}@ Override public void onTableChanged (@ Nullable Class
TableChanged, @ NonNull BaseModel. Action action) {// invalidate ();}});}
The above constructor,FlowContentObserver is designed to change data when database data changes,MClass,MWhere is the parameter required to create a common dbFlow query.
Step 2
The creation method returns the total amount of data in the current query table:
public int countItems() { try { mContentObserver.beginTransaction(); int size = SQLite.select() .from(mClass) .queryList() .size(); mContentObserver.endTransactionAndNotify(); return size; } catch (Exception e) { e.printStackTrace(); } return 0; }
Step 3
Rewrite related methods:
@Override public boolean isInvalid() { mContentObserver.setNotifyAllUris(true); return super.isInvalid(); }
Load initialization data
@ Override public void loadInitial (@ NonNull LoadInitialParams params, @ NonNull LoadInitialCallback Callback) {int totalCount = countItems (); if (totalCount = 0) {// return callback. onResult (Collections. EmptyList (), 0, 0); return;} // bound the size requested, based on known count // implement the paging Loading Function final int firstLoadPosition = computeInitialLoadPosition (params, totalCount ); final int firstLoadSize = computeInitialLoadSize (params, firstLoadPosition, totalCount); // loadRange is our own data query method List. List = loadRange (firstLoadPosition, firstLoadSize); if (list! = Null & list. size () = firstLoadSize) {callback. onResult (list, firstLoadPosition, totalCount);} else {// null list, or size doesn't match request-DB modified between count and load invalidate ();}}
The following two methods are used to transmit the local data to LiveData and add an external public method to change the data to be queried.
/*** Provides external data interfaces to facilitate data change ** @ param dataList * @ return */@ SuppressWarnings ("WeakerAccess") protected abstract List ConvertData (List DataList);/*** Return the rows from startPos to startPos + loadCount */@ Nullable public List LoadRange (int startPosition, int loadCount) {mContentObserver. beginTransaction (); List Ts = mWhere. limit (loadCount). offset (startPosition). queryList (); mContentObserver. endTransactionAndNotify (); return convertData (ts );}
After the initial loading callback is passed to the dispatch loading initialization PagedList, this method is called to load the additional page from DataSource.
@Override public void loadRange(@NonNull LoadRangeParams params, @NonNull LoadRangeCallback callback) { List list = loadRange(params.startPosition, params.loadSize); if (list != null) { callback.onResult(list); } else { invalidate(); } }
Step5
Usage:
new DataSource.Factory () { @Override public LimitOffsetDataSource create() { return new LimitOffsetDataSource (Session.class, context, where) { @Override protected List convertData(List dataList) { return dataList; } }; } };
In this way, you have created your ownDataSource. Factory. Note that the first type can only beInteger type, becauseLimitOffsetDataSource inheritedPositionalDataSource usesInteger type.
Summary
The above is all, and the two most critical cores are
* Adds a Database Listener, which must be called when the database changesInvalidate (); to refresh the dataThis is critical. Otherwise, the data cannot be automatically refreshed.
* Pass the queried local dataDataSource is ours.LoadRange (int startPosition, int loadCount) Method