io.objectbox.query.Query Java Examples
The following examples show how to use
io.objectbox.query.Query.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: IndexReaderRenewTest.java From objectbox-java with Apache License 2.0 | 6 votes |
@Test public void testOldReaderWithIndex() { final Box<EntityLongIndex> box = store.boxFor(EntityLongIndex.class); final int initialValue = 1; final Query<EntityLongIndex> query = box.query().equal(EntityLongIndex_.indexedLong, 0).build(); assertNull(query.findUnique()); System.out.println("BEFORE put: " + box.getReaderDebugInfo()); System.out.println("count before: " + box.count()); box.put(createEntityLongIndex(initialValue)); System.out.println("AFTER put: " + box.getReaderDebugInfo()); System.out.println("count after: " + box.count()); query.setParameter(EntityLongIndex_.indexedLong, initialValue); assertNotNull(query.findUnique()); query.setParameter(EntityLongIndex_.indexedLong, 0); assertNull(query.findUnique()); }
Example #2
Source File: MultipleDaysFragment.java From weather with Apache License 2.0 | 6 votes |
private void showStoredMultipleDaysWeather() { Query<MultipleDaysWeather> query = DbUtil.getMultipleDaysWeatherQuery(multipleDaysWeatherBox); query.subscribe().on(AndroidScheduler.mainThread()) .observer(new DataObserver<List<MultipleDaysWeather>>() { @Override public void onData(@NonNull List<MultipleDaysWeather> data) { if (data.size() > 0) { final Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { data.remove(0); mItemAdapter.clear(); mItemAdapter.add(data); } }, 500); } } }); }
Example #3
Source File: MainActivity.java From weather with Apache License 2.0 | 6 votes |
private void showStoredCurrentWeather() { Query<CurrentWeather> query = DbUtil.getCurrentWeatherQuery(currentWeatherBox); query.subscribe(subscriptions).on(AndroidScheduler.mainThread()) .observer(new DataObserver<List<CurrentWeather>>() { @Override public void onData(@NonNull List<CurrentWeather> data) { if (data.size() > 0) { hideEmptyLayout(); CurrentWeather currentWeather = data.get(0); if (isLoad) { tempTextView.setText(String.format(Locale.getDefault(), "%.0f°", currentWeather.getTemp())); descriptionTextView.setText(AppUtil.getWeatherStatus(currentWeather.getWeatherId(), AppUtil.isRTL(MainActivity.this))); humidityTextView.setText(String.format(Locale.getDefault(), "%d%%", currentWeather.getHumidity())); windTextView.setText(String.format(Locale.getDefault(), getResources().getString(R.string.wind_unit_label), currentWeather.getWindSpeed())); } else { tempTextView.setCurrentText(String.format(Locale.getDefault(), "%.0f°", currentWeather.getTemp())); descriptionTextView.setCurrentText(AppUtil.getWeatherStatus(currentWeather.getWeatherId(), AppUtil.isRTL(MainActivity.this))); humidityTextView.setCurrentText(String.format(Locale.getDefault(), "%d%%", currentWeather.getHumidity())); windTextView.setCurrentText(String.format(Locale.getDefault(), getResources().getString(R.string.wind_unit_label), currentWeather.getWindSpeed())); } animationView.setAnimation(AppUtil.getWeatherAnimation(currentWeather.getWeatherId())); animationView.playAnimation(); } } }); }
Example #4
Source File: ObjectBoxDB.java From Hentoid with Apache License 2.0 | 6 votes |
private Query<Content> queryContentUniversalContent( String queryStr, boolean filterFavourites, long[] additionalIds, int orderField, boolean orderDesc) { QueryBuilder<Content> query = store.boxFor(Content.class).query(); query.in(Content_.status, libraryStatus); if (filterFavourites) query.equal(Content_.favourite, true); query.contains(Content_.title, queryStr, QueryBuilder.StringOrder.CASE_INSENSITIVE); query.or().equal(Content_.uniqueSiteId, queryStr); // query.or().link(Content_.attributes).contains(Attribute_.name, queryStr, QueryBuilder.StringOrder.CASE_INSENSITIVE); // Use of or() here is not possible yet with ObjectBox v2.3.1 query.or().in(Content_.id, additionalIds); applySortOrder(query, orderField, orderDesc); return query.build(); }
Example #5
Source File: RxQuery.java From ObjectBoxRxJava with Apache License 2.0 | 6 votes |
/** * The returned Single emits one Query result as a List. */ public static <T> Single<List<T>> single(final Query<T> query) { return Single.create(new SingleOnSubscribe<List<T>>() { @Override public void subscribe(final SingleEmitter<List<T>> emitter) throws Exception { query.subscribe().single().observer(new DataObserver<List<T>>() { @Override public void onData(List<T> data) { if (!emitter.isDisposed()) { emitter.onSuccess(data); } } }); // no need to cancel, single never subscribes } }); }
Example #6
Source File: RxQuery.java From ObjectBoxRxJava with Apache License 2.0 | 6 votes |
/** * The returned Observable emits Query results as Lists. * Never completes, so you will get updates when underlying data changes. */ public static <T> Observable<List<T>> observable(final Query<T> query) { return Observable.create(new ObservableOnSubscribe<List<T>>() { @Override public void subscribe(final ObservableEmitter<List<T>> emitter) throws Exception { final DataSubscription dataSubscription = query.subscribe().observer(new DataObserver<List<T>>() { @Override public void onData(List<T> data) { if (!emitter.isDisposed()) { emitter.onNext(data); } } }); emitter.setCancellable(new Cancellable() { @Override public void cancel() throws Exception { dataSubscription.cancel(); } }); } }); }
Example #7
Source File: RxQuery.java From ObjectBoxRxJava with Apache License 2.0 | 6 votes |
static <T> void createListItemEmitter(final Query<T> query, final FlowableEmitter<T> emitter) { final DataSubscription dataSubscription = query.subscribe().observer(new DataObserver<List<T>>() { @Override public void onData(List<T> data) { for (T datum : data) { if (emitter.isCancelled()) { return; } else { emitter.onNext(datum); } } if (!emitter.isCancelled()) { emitter.onComplete(); } } }); emitter.setCancellable(new Cancellable() { @Override public void cancel() throws Exception { dataSubscription.cancel(); } }); }
Example #8
Source File: ObjectBoxDB.java From Hentoid with Apache License 2.0 | 5 votes |
long insertContent(Content content) { List<Attribute> attributes = content.getAttributes(); Box<Attribute> attrBox = store.boxFor(Attribute.class); Query attrByUniqueKey = attrBox.query().equal(Attribute_.type, 0).equal(Attribute_.name, "").build(); return store.callInTxNoException(() -> { // Master data management managed manually // Ensure all known attributes are replaced by their ID before being inserted // Watch https://github.com/objectbox/objectbox-java/issues/509 for a lighter solution based on @Unique annotation Attribute dbAttr; Attribute inputAttr; if (attributes != null) for (int i = 0; i < attributes.size(); i++) { inputAttr = attributes.get(i); dbAttr = (Attribute) attrByUniqueKey.setParameter(Attribute_.name, inputAttr.getName()) .setParameter(Attribute_.type, inputAttr.getType().getCode()) .findFirst(); if (dbAttr != null) { attributes.set(i, dbAttr); // If existing -> set the existing attribute dbAttr.addLocationsFrom(inputAttr); attrBox.put(dbAttr); } else { inputAttr.setName(inputAttr.getName().toLowerCase().trim()); // If new -> normalize the attribute } } return store.boxFor(Content.class).put(content); }); }
Example #9
Source File: RelationEagerTest.java From objectbox-java with Apache License 2.0 | 5 votes |
@Test public void testEagerToSingle_NoResult() { Query<Order> query = orderBox.query().eager(Order_.customer).build(); query.find(); query.findFirst(); query.forEach(data -> { }); }
Example #10
Source File: ObjectBoxDB.java From Hentoid with Apache License 2.0 | 5 votes |
private long[] selectFilteredContent(List<Attribute> attrs, boolean filterFavourites) { if (null == attrs || attrs.isEmpty()) return new long[0]; // Pre-build queries to reuse them efficiently within the loops QueryBuilder<Content> contentFromSourceQueryBuilder = store.boxFor(Content.class).query(); contentFromSourceQueryBuilder.in(Content_.status, libraryStatus); contentFromSourceQueryBuilder.equal(Content_.site, 1); if (filterFavourites) contentFromSourceQueryBuilder.equal(Content_.favourite, true); Query<Content> contentFromSourceQuery = contentFromSourceQueryBuilder.build(); QueryBuilder<Content> contentFromAttributesQueryBuilder = store.boxFor(Content.class).query(); contentFromAttributesQueryBuilder.in(Content_.status, libraryStatus); if (filterFavourites) contentFromSourceQueryBuilder.equal(Content_.favourite, true); contentFromAttributesQueryBuilder.link(Content_.attributes) .equal(Attribute_.type, 0) .equal(Attribute_.name, ""); Query<Content> contentFromAttributesQuery = contentFromAttributesQueryBuilder.build(); // Cumulative query loop // Each iteration restricts the results of the next because advanced search uses an AND logic List<Long> results = Collections.emptyList(); long[] ids; for (Attribute attr : attrs) { if (attr.getType().equals(AttributeType.SOURCE)) { ids = contentFromSourceQuery.setParameter(Content_.site, attr.getId()).findIds(); } else { ids = contentFromAttributesQuery.setParameter(Attribute_.type, attr.getType().getCode()) .setParameter(Attribute_.name, attr.getName()).findIds(); } if (results.isEmpty()) results = Helper.getListFromPrimitiveArray(ids); else { // Filter results with newly found IDs (only common IDs should stay) List<Long> idsAsList = Helper.getListFromPrimitiveArray(ids); results.retainAll(idsAsList); } } return Helper.getPrimitiveLongArrayFromList(results); }
Example #11
Source File: ObjectBoxDB.java From Hentoid with Apache License 2.0 | 5 votes |
long countContentUniversal(String queryStr, boolean filterFavourites) { // Due to objectBox limitations (see https://github.com/objectbox/objectbox-java/issues/497 and https://github.com/objectbox/objectbox-java/issues/201) // querying Content and attributes have to be done separately Query<Content> contentAttrSubQuery = queryContentUniversalAttributes(queryStr, filterFavourites); Query<Content> query = queryContentUniversalContent(queryStr, filterFavourites, contentAttrSubQuery.findIds(), Preferences.Constant.ORDER_FIELD_NONE, false); return query.count(); }
Example #12
Source File: RxQuery.java From objectbox-java with Apache License 2.0 | 5 votes |
static <T> void createListItemEmitter(final Query<T> query, final FlowableEmitter<T> emitter) { final DataSubscription dataSubscription = query.subscribe().observer(data -> { for (T datum : data) { if (emitter.isCancelled()) { return; } else { emitter.onNext(datum); } } if (!emitter.isCancelled()) { emitter.onComplete(); } }); emitter.setCancellable(dataSubscription::cancel); }
Example #13
Source File: RxQuery.java From objectbox-java with Apache License 2.0 | 5 votes |
/** * The returned Observable emits Query results as Lists. * Never completes, so you will get updates when underlying data changes * (see {@link Query#subscribe()} for details). */ public static <T> Observable<List<T>> observable(final Query<T> query) { return Observable.create(emitter -> { final DataSubscription dataSubscription = query.subscribe().observer(data -> { if (!emitter.isDisposed()) { emitter.onNext(data); } }); emitter.setCancellable(dataSubscription::cancel); }); }
Example #14
Source File: RxQuery.java From objectbox-java with Apache License 2.0 | 5 votes |
/** * The returned Single emits one Query result as a List. */ public static <T> Single<List<T>> single(final Query<T> query) { return Single.create(emitter -> { query.subscribe().single().observer(data -> { if (!emitter.isDisposed()) { emitter.onSuccess(data); } }); // no need to cancel, single never subscribes }); }
Example #15
Source File: ObjectBoxRandomDataSource.java From Hentoid with Apache License 2.0 | 5 votes |
private List<T> shuffleRandomSort(Query<T> query, int startPosition, int loadCount) { LazyList<T> lazyList = query.findLazy(); List<Integer> order = new ArrayList<>(); for (int i = 0; i < lazyList.size(); i++) order.add(i); Collections.shuffle(order, new Random(RandomSeedSingleton.getInstance().getSeed())); int maxPage = Math.min(startPosition + loadCount, order.size()); List<T> result = new ArrayList<>(); for (int i = startPosition; i < maxPage; i++) { result.add(lazyList.get(order.get(i))); } return result; }
Example #16
Source File: ObjectBoxDAO.java From Hentoid with Apache License 2.0 | 5 votes |
private LiveData<PagedList<Content>> getPagedContent( int mode, String filter, List<Attribute> metadata, int orderField, boolean orderDesc, boolean favouritesOnly, boolean loadAll) { boolean isRandom = (orderField == Preferences.Constant.ORDER_FIELD_RANDOM); Query<Content> query; if (Mode.SEARCH_CONTENT_MODULAR == mode) { query = db.queryContentSearchContent(filter, metadata, favouritesOnly, orderField, orderDesc); } else { // Mode.SEARCH_CONTENT_UNIVERSAL query = db.queryContentUniversal(filter, favouritesOnly, orderField, orderDesc); } int nbPages = Preferences.getContentPageQuantity(); int initialLoad = nbPages * 2; if (loadAll) { // Trump Android's algorithm by setting a number of pages higher that the actual number of results // to avoid having a truncated result set (see issue #501) initialLoad = (int) Math.ceil(query.count() * 1.0 / nbPages) * nbPages; } PagedList.Config cfg = new PagedList.Config.Builder().setEnablePlaceholders(!loadAll).setInitialLoadSizeHint(initialLoad).setPageSize(nbPages).build(); return new LivePagedListBuilder<>( isRandom ? new ObjectBoxRandomDataSource.RandomDataSourceFactory<>(query) : new ObjectBoxDataSource.Factory<>(query), cfg ).build(); }
Example #17
Source File: ObjectBoxDB.java From Hentoid with Apache License 2.0 | 5 votes |
Query<Content> selectAllLibraryBooksQ(boolean favsOnly) { // All statuses except SAVED, DOWNLOADING, PAUSED and ERROR that imply the book is in the download queue int[] storedContentStatus = new int[]{ StatusContent.DOWNLOADED.getCode(), StatusContent.MIGRATED.getCode(), StatusContent.IGNORED.getCode(), StatusContent.UNHANDLED_ERROR.getCode(), StatusContent.CANCELED.getCode(), StatusContent.ONLINE.getCode() }; QueryBuilder<Content> query = store.boxFor(Content.class).query().in(Content_.status, storedContentStatus); if (favsOnly) query.equal(Content_.favourite, true); return query.build(); }
Example #18
Source File: ObjectBoxDB.java From Hentoid with Apache License 2.0 | 5 votes |
Query<Content> selectAllQueueBooksQ() { int[] storedContentStatus = new int[]{ StatusContent.SAVED.getCode(), StatusContent.DOWNLOADING.getCode(), StatusContent.PAUSED.getCode(), StatusContent.ERROR.getCode() }; return store.boxFor(Content.class).query().in(Content_.status, storedContentStatus).build(); }
Example #19
Source File: ObjectBoxDB.java From Hentoid with Apache License 2.0 | 5 votes |
Query<Content> queryContentSearchContent( String title, List<Attribute> metadata, boolean filterFavourites, int orderField, boolean orderDesc) { AttributeMap metadataMap = new AttributeMap(); metadataMap.addAll(metadata); boolean hasTitleFilter = (title != null && title.length() > 0); boolean hasSiteFilter = metadataMap.containsKey(AttributeType.SOURCE) && (metadataMap.get(AttributeType.SOURCE) != null) && !(metadataMap.get(AttributeType.SOURCE).isEmpty()); boolean hasTagFilter = metadataMap.keySet().size() > (hasSiteFilter ? 1 : 0); QueryBuilder<Content> query = store.boxFor(Content.class).query(); query.in(Content_.status, libraryStatus); if (hasSiteFilter) query.in(Content_.site, getIdsFromAttributes(metadataMap.get(AttributeType.SOURCE))); if (filterFavourites) query.equal(Content_.favourite, true); if (hasTitleFilter) query.contains(Content_.title, title); if (hasTagFilter) { for (Map.Entry<AttributeType, List<Attribute>> entry : metadataMap.entrySet()) { AttributeType attrType = entry.getKey(); if (!attrType.equals(AttributeType.SOURCE)) { // Not a "real" attribute in database List<Attribute> attrs = entry.getValue(); if (attrs != null && !attrs.isEmpty()) { query.in(Content_.id, selectFilteredContent(attrs, false)); } } } } applySortOrder(query, orderField, orderDesc); return query.build(); }
Example #20
Source File: ObjectBoxDB.java From Hentoid with Apache License 2.0 | 5 votes |
private Query<Content> queryContentUniversalAttributes(String queryStr, boolean filterFavourites) { QueryBuilder<Content> query = store.boxFor(Content.class).query(); query.in(Content_.status, libraryStatus); if (filterFavourites) query.equal(Content_.favourite, true); query.link(Content_.attributes).contains(Attribute_.name, queryStr, QueryBuilder.StringOrder.CASE_INSENSITIVE); return query.build(); }
Example #21
Source File: ObjectBoxDB.java From Hentoid with Apache License 2.0 | 5 votes |
Query<Content> queryContentUniversal( String queryStr, boolean filterFavourites, int orderField, boolean orderDesc) { // Due to objectBox limitations (see https://github.com/objectbox/objectbox-java/issues/497 and https://github.com/objectbox/objectbox-java/issues/201) // querying Content and attributes have to be done separately Query<Content> contentAttrSubQuery = queryContentUniversalAttributes(queryStr, filterFavourites); return queryContentUniversalContent(queryStr, filterFavourites, contentAttrSubQuery.findIds(), orderField, orderDesc); }
Example #22
Source File: ObjectBoxDB.java From Hentoid with Apache License 2.0 | 5 votes |
private static long[] shuffleRandomSortId(Query<Content> query) { LazyList<Content> lazyList = query.findLazy(); List<Integer> order = new ArrayList<>(); for (int i = 0; i < lazyList.size(); i++) order.add(i); Collections.shuffle(order, new Random(RandomSeedSingleton.getInstance().getSeed())); List<Long> result = new ArrayList<>(); for (int i = 0; i < order.size(); i++) { result.add(lazyList.get(order.get(i)).getId()); } return Helper.getPrimitiveLongArrayFromList(result); }
Example #23
Source File: ObjectBoxDB.java From Hentoid with Apache License 2.0 | 5 votes |
long[] selectContentSearchId(String title, List<Attribute> tags, boolean filterFavourites, int orderField, boolean orderDesc) { long[] result; Query<Content> query = queryContentSearchContent(title, tags, filterFavourites, orderField, orderDesc); if (orderField != Preferences.Constant.ORDER_FIELD_RANDOM) { result = query.findIds(); } else { result = shuffleRandomSortId(query); } return result; }
Example #24
Source File: ObjectBoxDB.java From Hentoid with Apache License 2.0 | 5 votes |
long[] selectContentUniversalId(String queryStr, boolean filterFavourites, int orderField, boolean orderDesc) { long[] result; // Due to objectBox limitations (see https://github.com/objectbox/objectbox-java/issues/497 and https://github.com/objectbox/objectbox-java/issues/201) // querying Content and attributes have to be done separately Query<Content> contentAttrSubQuery = queryContentUniversalAttributes(queryStr, filterFavourites); Query<Content> query = queryContentUniversalContent(queryStr, filterFavourites, contentAttrSubQuery.findIds(), orderField, orderDesc); if (orderField != Preferences.Constant.ORDER_FIELD_RANDOM) { result = query.findIds(); } else { result = shuffleRandomSortId(query); } return result; }
Example #25
Source File: ObjectBoxDB.java From Hentoid with Apache License 2.0 | 5 votes |
private Query<Attribute> queryAvailableAttributes( @NonNull final AttributeType type, String filter, long[] filteredContent) { QueryBuilder<Attribute> query = store.boxFor(Attribute.class).query(); query.equal(Attribute_.type, type.getCode()); if (filter != null && !filter.trim().isEmpty()) query.contains(Attribute_.name, filter.trim(), QueryBuilder.StringOrder.CASE_INSENSITIVE); if (filteredContent.length > 0) query.link(Attribute_.contents).in(Content_.id, filteredContent).in(Content_.status, libraryStatus); else query.link(Attribute_.contents).in(Content_.status, libraryStatus); return query.build(); }
Example #26
Source File: CollectArticleTableManager.java From WanAndroid with MIT License | 5 votes |
public Observable<Boolean> isExists(String title, String author) { return Observable.create((emitter -> { Query query = CollectArticleTableManager.collectArticleBox.query().equal(CollectArticleDB_.title, title).equal(CollectArticleDB_.author, author).build(); List<CollectArticleDB> collectArticleDBList = query.find(); if (collectArticleDBList == null || collectArticleDBList.size() == 0) { emitter.onNext(false); } else { emitter.onNext(true); } emitter.onComplete(); })); }
Example #27
Source File: CollectArticleTableManager.java From WanAndroid with MIT License | 5 votes |
public Observable<List<CollectArticleDB>> getAllCollectArticle() { return Observable.create((emitter -> { String accountName = AccountManager.getInstance().getCurrentAccount().getUsername(); Query query = CollectArticleTableManager.collectArticleBox.query().equal(CollectArticleDB_.accountName, accountName).build(); List<CollectArticleDB> data = query.find(); emitter.onNext(data); emitter.onComplete(); })); }
Example #28
Source File: CollectArticleTableManager.java From WanAndroid with MIT License | 5 votes |
public Observable<Boolean> deleteCollectArticle(String title, String author) { return Observable.create(emitter -> { Query query = CollectArticleTableManager.collectArticleBox.query().equal(CollectArticleDB_.title, title).equal(CollectArticleDB_.author, author).build(); query.remove(); emitter.onNext(true); emitter.onComplete(); }); }
Example #29
Source File: PortfolioRepository.java From Building-Professional-Android-Applications with MIT License | 5 votes |
public Observable<StockPortfolioItem> getPortfolioItems() { Query<StockPortfolioItem> query = portfolioItemBox.query() .build(); return RxQuery.observable(query) .take(1) .flatMap(Observable::fromIterable); }
Example #30
Source File: ObjectBoxDB.java From Hentoid with Apache License 2.0 | 5 votes |
Query<ImageFile> selectDownloadedImagesFromContent(long id) { QueryBuilder<ImageFile> builder = store.boxFor(ImageFile.class).query(); builder.equal(ImageFile_.contentId, id); builder.equal(ImageFile_.status, StatusContent.DOWNLOADED.getCode()); builder.order(ImageFile_.order); return builder.build(); }