io.objectbox.BoxStore Java Examples

The following examples show how to use io.objectbox.BoxStore. 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: QueryTest.java    From objectbox-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testSetParameterInt() {
    String versionNative = BoxStore.getVersionNative();
    String minVersion = "1.5.1-2018-06-21";
    String versionStart = versionNative.substring(0, minVersion.length());
    assertTrue(versionStart, versionStart.compareTo(minVersion) >= 0);

    putTestEntitiesScalars();
    Query<TestEntity> query = box.query().equal(simpleInt, 2007).parameterAlias("foo").build();
    assertEquals(8, query.findUnique().getId());
    query.setParameter(simpleInt, 2004);
    assertEquals(5, query.findUnique().getId());

    query.setParameter("foo", 2002);
    assertEquals(3, query.findUnique().getId());
}
 
Example #2
Source File: QueryPublisher.java    From objectbox-java with Apache License 2.0 6 votes vote down vote up
@Override
public synchronized void subscribe(DataObserver<List<T>> observer, @Nullable Object param) {
    final BoxStore store = box.getStore();
    if (objectClassObserver == null) {
        objectClassObserver = objectClass -> publish();
    }
    if (observers.isEmpty()) {
        if (objectClassSubscription != null) {
            throw new IllegalStateException("Existing subscription found");
        }

        // Weak: Query references QueryPublisher, which references objectClassObserver.
        // Query's DataSubscription references QueryPublisher, which references Query.
        // --> Query and its DataSubscription keep objectClassSubscription alive.
        // --> If both are gone, the app could not possibly unsubscribe.
        // --> OK for objectClassSubscription to be GCed and thus unsubscribed?
        // --> However, still subscribed observers to the query will NOT be notified anymore.
        objectClassSubscription = store.subscribe(box.getEntityClass())
                .weak()
                .onlyChanges()
                .observer(objectClassObserver);
    }
    observers.add(observer);
}
 
Example #3
Source File: RxBoxStore.java    From ObjectBoxRxJava with Apache License 2.0 6 votes vote down vote up
/**
 * Using the returned Observable, you can be notified about data changes.
 * Once a transaction is committed, you will get info on classes with changed Objects.
 */
public static <T> Observable<Class> observable(final BoxStore boxStore) {
    return Observable.create(new ObservableOnSubscribe<Class>() {
        @Override
        public void subscribe(final ObservableEmitter<Class> emitter) throws Exception {
            final DataSubscription dataSubscription = boxStore.subscribe().observer(new DataObserver<Class>() {
                @Override
                public void onData(Class data) {
                    if (!emitter.isDisposed()) {
                        emitter.onNext(data);
                    }
                }
            });
            emitter.setCancellable(new Cancellable() {
                @Override
                public void cancel() throws Exception {
                    dataSubscription.cancel();
                }
            });
        }
    });
}
 
Example #4
Source File: ToMany.java    From objectbox-java with Apache License 2.0 6 votes vote down vote up
private void ensureBoxes() {
    if (targetBox == null) {
        Field boxStoreField = ReflectionCache.getInstance().getField(entity.getClass(), "__boxStore");
        try {
            boxStore = (BoxStore) boxStoreField.get(entity);
            if (boxStore == null) {
                throw new DbDetachedException("Cannot resolve relation for detached entities, " +
                        "call box.attach(entity) beforehand.");
            }
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
        entityBox = boxStore.boxFor(relationInfo.sourceInfo.getEntityClass());
        targetBox = boxStore.boxFor(relationInfo.targetInfo.getEntityClass());
    }
}
 
Example #5
Source File: AbstractObjectBoxTest.java    From Hentoid with Apache License 2.0 5 votes vote down vote up
@AfterClass
public static void tearDown() throws Exception {
    if (store != null) {
        store.close();
        store = null;
    }
    BoxStore.deleteAllFiles(TEST_DIRECTORY);
}
 
Example #6
Source File: EntityLongIndex_.java    From objectbox-java with Apache License 2.0 5 votes vote down vote up
@Override
public CursorFactory<EntityLongIndex> getCursorFactory() {
    return new CursorFactory<EntityLongIndex>() {
        @Override
        public Cursor<EntityLongIndex> createCursor(Transaction tx, long cursorHandle, @Nullable BoxStore boxStoreForEntities) {
            return new EntityLongIndexCursor(tx, cursorHandle, boxStoreForEntities);
        }
    };
}
 
Example #7
Source File: RxBoxStore.java    From objectbox-java with Apache License 2.0 5 votes vote down vote up
/**
 * Using the returned Observable, you can be notified about data changes.
 * Once a transaction is committed, you will get info on classes with changed Objects.
 */
public static <T> Observable<Class> observable(final BoxStore boxStore) {
    return Observable.create(emitter -> {
        final DataSubscription dataSubscription = boxStore.subscribe().observer(data -> {
            if (!emitter.isDisposed()) {
                emitter.onNext(data);
            }
        });
        emitter.setCancellable(dataSubscription::cancel);
    });
}
 
Example #8
Source File: MainActivity.java    From andela-crypto-app with Apache License 2.0 5 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    ButterKnife.bind(this);

    setSupportActionBar(toolbar);

    BoxStore boxStore = ((AndelaTrackChallenge) getApplicationContext()).getBoxStore();
    userBox = boxStore.boxFor(User.class);
    countryBox = boxStore.boxFor(Country.class);
    user = userBox.query().build().findFirst();

    profileDialog = ProfileDialog.newInstance(((dialog, which) -> logout()));

    // Configure sign-in to request the user's ID, email address, and basic
    // profile. ID and basic profile are included in DEFAULT_SIGN_IN.
    GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
            .requestEmail()
            .build();
    // Build a GoogleApiClient with access to the Google Sign-In Api and the
    // options specified by gso.
    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .enableAutoManage(this /* FragmentActivity */, this /* OnConnectionFailedListener */)
            .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
            .build();
    init();

    fab.setOnClickListener(v ->
            CurrencyPickerFragment
                    .newInstance(countryBox.getAll())
                    .show(MainActivity.this.getSupportFragmentManager(), "currency-picker"));

    snackProgressBarManager = new SnackProgressBarManager(coordinatorLayout)
            .setProgressBarColor(R.color.colorAccent)
            .setOverlayLayoutAlpha(0.6f);
}
 
Example #9
Source File: RxBoxStore.java    From objectbox-java with Apache License 2.0 5 votes vote down vote up
/**
 * Using the returned Observable, you can be notified about data changes.
 * Once a transaction is committed, you will get info on classes with changed Objects.
 */
@SuppressWarnings("rawtypes") // BoxStore observer may return any (entity) type.
public static Observable<Class> observable(BoxStore boxStore) {
    return Observable.create(emitter -> {
        final DataSubscription dataSubscription = boxStore.subscribe().observer(data -> {
            if (!emitter.isDisposed()) {
                emitter.onNext(data);
            }
        });
        emitter.setCancellable(dataSubscription::cancel);
    });
}
 
Example #10
Source File: ObjectBoxDB.java    From Hentoid with Apache License 2.0 5 votes vote down vote up
public static synchronized ObjectBoxDB getInstance(BoxStore store) {
    // Use application context only
    if (instance == null) {
        instance = new ObjectBoxDB(store);
    }

    return instance;
}
 
Example #11
Source File: AbstractObjectBoxTest.java    From Hentoid with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public static void setUp() throws Exception {
    // delete database files before each test to start with a clean database
    BoxStore.deleteAllFiles(TEST_DIRECTORY);
    store = MyObjectBox.builder()
            // add directory flag to change where ObjectBox puts its database files
            .directory(TEST_DIRECTORY)
            // optional: add debug flags for more detailed ObjectBox log output
            .debugFlags(DebugFlags.LOG_QUERIES | DebugFlags.LOG_QUERY_PARAMETERS)
            .build();
}
 
Example #12
Source File: HourlyActivity.java    From weather with Apache License 2.0 5 votes vote down vote up
private void setVariables() {
  Intent intent = getIntent();
  fiveDayWeather = intent.getParcelableExtra(Constants.FIVE_DAY_WEATHER_ITEM);
  BoxStore boxStore = MyApplication.getBoxStore();
  itemHourlyDBBox = boxStore.boxFor(ItemHourlyDB.class);
  cardView.setCardBackgroundColor(fiveDayWeather.getColor());
  Calendar calendar = Calendar.getInstance(TimeZone.getDefault());
  calendar.setTimeInMillis(fiveDayWeather.getDt() * 1000L);
  if (AppUtil.isRTL(this)) {
    dayNameTextView.setText(Constants.DAYS_OF_WEEK_PERSIAN[calendar.get(Calendar.DAY_OF_WEEK) - 1]);
  } else {
    dayNameTextView.setText(Constants.DAYS_OF_WEEK[calendar.get(Calendar.DAY_OF_WEEK) - 1]);
  }
  if (fiveDayWeather.getMaxTemp() < 0 && fiveDayWeather.getMaxTemp() > -0.5) {
    fiveDayWeather.setMaxTemp(0);
  }
  if (fiveDayWeather.getMinTemp() < 0 && fiveDayWeather.getMinTemp() > -0.5) {
    fiveDayWeather.setMinTemp(0);
  }
  if (fiveDayWeather.getTemp() < 0 && fiveDayWeather.getTemp() > -0.5) {
    fiveDayWeather.setTemp(0);
  }
  tempTextView.setText(String.format(Locale.getDefault(), "%.0f°", fiveDayWeather.getTemp()));
  minTempTextView.setText(String.format(Locale.getDefault(), "%.0f°", fiveDayWeather.getMinTemp()));
  maxTempTextView.setText(String.format(Locale.getDefault(), "%.0f°", fiveDayWeather.getMaxTemp()));
  animationView.setAnimation(AppUtil.getWeatherAnimation(fiveDayWeather.getWeatherId()));
  animationView.playAnimation();
  typeface = Typeface.createFromAsset(getAssets(), "fonts/Vazir.ttf");
}
 
Example #13
Source File: MainActivity.java    From weather with Apache License 2.0 5 votes vote down vote up
private void initValues() {
  prefser = new Prefser(this);
  apiService = ApiClient.getClient().create(ApiService.class);
  BoxStore boxStore = MyApplication.getBoxStore();
  currentWeatherBox = boxStore.boxFor(CurrentWeather.class);
  fiveDayWeatherBox = boxStore.boxFor(FiveDayWeather.class);
  itemHourlyDBBox = boxStore.boxFor(ItemHourlyDB.class);
  swipeContainer.setColorSchemeResources(android.R.color.holo_blue_bright,
      android.R.color.holo_green_light,
      android.R.color.holo_orange_light,
      android.R.color.holo_red_light);
  swipeContainer.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {

    @Override
    public void onRefresh() {
      cityInfo = prefser.get(Constants.CITY_INFO, CityInfo.class, null);
      if (cityInfo != null) {
        long lastStored = prefser.get(Constants.LAST_STORED_CURRENT, Long.class, 0L);
        if (AppUtil.isTimePass(lastStored)) {
          requestWeather(cityInfo.getName(), false);
        } else {
          swipeContainer.setRefreshing(false);
        }
      } else {
        swipeContainer.setRefreshing(false);
      }
    }

  });
  bar.setNavigationOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
      showAboutFragment();
    }
  });
  typeface = Typeface.createFromAsset(getAssets(), "fonts/Vazir.ttf");
}
 
Example #14
Source File: MyApplication.java    From Mp3Cutter with GNU General Public License v3.0 4 votes vote down vote up
public BoxStore getBoxStore(){
    return mBoxStore;
}
 
Example #15
Source File: ObjectBoxDB.java    From Hentoid with Apache License 2.0 4 votes vote down vote up
private ObjectBoxDB(BoxStore store) {
    this.store = store;
}
 
Example #16
Source File: ObectBoxModule.java    From Anecdote with Apache License 2.0 4 votes vote down vote up
public ObectBoxModule(BoxStore boxStore) {
    bind(BoxStore.class).toInstance(boxStore);
}
 
Example #17
Source File: HistoryRepository.java    From andela-crypto-app with Apache License 2.0 4 votes vote down vote up
public HistoryRepository(Context context, BoxStore boxStore) {
    this.boxStore = boxStore;

    historyBox = this.boxStore.boxFor(HistoryDb.class);
}
 
Example #18
Source File: ObjectBoxDAO.java    From Hentoid with Apache License 2.0 4 votes vote down vote up
public ObjectBoxDAO(BoxStore store) {
    db = ObjectBoxDB.getInstance(store);
}
 
Example #19
Source File: AndelaTrackChallenge.java    From andela-crypto-app with Apache License 2.0 4 votes vote down vote up
public BoxStore getBoxStore() {
    return boxStore;
}
 
Example #20
Source File: MockQuery.java    From objectbox-java with Apache License 2.0 4 votes vote down vote up
public BoxStore getBoxStore() {
    return boxStore;
}
 
Example #21
Source File: IndexReaderRenewTest.java    From objectbox-java with Apache License 2.0 4 votes vote down vote up
@Override
protected BoxStore createBoxStore() {
    return MyObjectBox.builder().directory(boxStoreDir).build();
}
 
Example #22
Source File: AbstractRelationTest.java    From objectbox-java with Apache License 2.0 4 votes vote down vote up
@After
public void deleteDbFiles() {
    BoxStore.deleteAllFiles(new File(BoxStoreBuilder.DEFAULT_NAME));
}
 
Example #23
Source File: AbstractRelationTest.java    From objectbox-java with Apache License 2.0 4 votes vote down vote up
@Override
protected BoxStore createBoxStore() {
    return MyObjectBox.builder().baseDirectory(boxStoreDir)
            .debugFlags(DebugFlags.LOG_TRANSACTIONS_READ | DebugFlags.LOG_TRANSACTIONS_WRITE)
            .build();
}
 
Example #24
Source File: CustomerCursor.java    From objectbox-java with Apache License 2.0 4 votes vote down vote up
public CustomerCursor(Transaction tx, long cursor, BoxStore boxStore) {
    super(tx, cursor, PROPERTIES, boxStore);
}
 
Example #25
Source File: MockQuery.java    From objectbox-java with Apache License 2.0 4 votes vote down vote up
public BoxStore getBoxStore() {
    return boxStore;
}
 
Example #26
Source File: MultipleDaysFragment.java    From weather with Apache License 2.0 4 votes vote down vote up
private void initVariables() {
  activity = getActivity();
  prefser = new Prefser(activity);
  BoxStore boxStore = MyApplication.getBoxStore();
  multipleDaysWeatherBox = boxStore.boxFor(MultipleDaysWeather.class);
}
 
Example #27
Source File: ObjectBox.java    From WanAndroid with MIT License 4 votes vote down vote up
public static BoxStore getBoxStore(){
    return boxStore;
}
 
Example #28
Source File: ObjectBoxModule.java    From Building-Professional-Android-Applications with MIT License 4 votes vote down vote up
@Provides
@Singleton
BoxStore provideAppDatabase(Application application) {
    return MyObjectBox.builder().androidContext(application).build();
}
 
Example #29
Source File: ObjectBoxModule.java    From Building-Professional-Android-Applications with MIT License 4 votes vote down vote up
@Provides
@Named("stockPortfolioItem")
@Singleton
Box<StockPortfolioItem> providePortfolioRepository(BoxStore boxStore) {
    return boxStore.boxFor(StockPortfolioItem.class);
}
 
Example #30
Source File: MockQuery.java    From ObjectBoxRxJava with Apache License 2.0 4 votes vote down vote up
public BoxStore getBoxStore() {
    return boxStore;
}