private void setData() { RealmResults<RealmDemoData> result = mRealm.where(RealmDemoData.class).findAll(); RealmPieDataSet<RealmDemoData> set = new RealmPieDataSet<RealmDemoData>(result, "yValue", "label"); set.setColors(ColorTemplate.VORDIPLOM_COLORS); set.setLabel("Example market share"); set.setSliceSpace(2); // create a data object with the dataset list PieData data = new PieData(set); styleData(data); data.setValueTextColor(Color.WHITE); data.setValueTextSize(12f); // set data mChart.setData(data); mChart.animateY(1400); }
private RealmResults<Contact> searchContacts() { Contact c = Parcels.unwrap(getIntent().getParcelableExtra(EXTRA_SEARCH_FILTERS)); realm = Realm.getDefaultInstance(); RealmQuery<Contact> query = realm.where(Contact.class); query.contains(LASTNAME, c.lastName, Case.INSENSITIVE) .or() .contains(FIRSTNAME, c.lastName, Case.INSENSITIVE); if (!c.owner) { query.equalTo(OWNER, false); } if (!c.cornac) { query.equalTo(CORNAC, false); } if (!c.vet) { query.equalTo(VET, false); } return query.findAll(); }
/** * Get all for a specific filters * @return */ @Override public Flowable<Optional<List<T>>> getAll(Filter filter, SortingMode sortingMode) { Realm realm = Realm.getDefaultInstance(); RealmQuery<T> query = realm.where(clazz); query = filterToQuery(filter, query); RealmResults<T> items; if(sortingMode != null && sortingMode.entries.size() > 0) { items = applySortingMode(sortingMode, query); } else { items = query.findAll(); } List<T> copies = realm.copyFromRealm(items); realm.close(); return Flowable.just(Optional.wrap(copies)); }
private void setData() { RealmResults<RealmDemoData> result = mRealm.where(RealmDemoData.class).findAll(); RealmLineDataSet<RealmDemoData> set = new RealmLineDataSet<RealmDemoData>(result, "xValue", "yValue"); set.setMode(LineDataSet.Mode.CUBIC_BEZIER); set.setLabel("Realm LineDataSet"); set.setDrawCircleHole(false); set.setColor(ColorTemplate.rgb("#FF5722")); set.setCircleColor(ColorTemplate.rgb("#FF5722")); set.setLineWidth(1.8f); set.setCircleRadius(3.6f); ArrayList<ILineDataSet> dataSets = new ArrayList<ILineDataSet>(); dataSets.add(set); // add the dataset // create a data object with the dataset list LineData data = new LineData(dataSets); styleData(data); // set data mChart.setData(data); mChart.animateY(1400, Easing.EasingOption.EaseInOutQuart); }
private void setData() { RealmResults<RealmDemoData> result = mRealm.where(RealmDemoData.class).findAll(); RealmCandleDataSet<RealmDemoData> set = new RealmCandleDataSet<RealmDemoData>(result, "xValue", "high", "low", "open", "close"); set.setLabel("Realm CandleDataSet"); set.setShadowColor(Color.DKGRAY); set.setShadowWidth(0.7f); set.setDecreasingColor(Color.RED); set.setDecreasingPaintStyle(Paint.Style.FILL); set.setIncreasingColor(Color.rgb(122, 242, 84)); set.setIncreasingPaintStyle(Paint.Style.STROKE); set.setNeutralColor(Color.BLUE); ArrayList<ICandleDataSet> dataSets = new ArrayList<ICandleDataSet>(); dataSets.add(set); // add the dataset // create a data object with the dataset list CandleData data = new CandleData(dataSets); styleData(data); // set data mChart.setData(data); mChart.animateY(1400, Easing.EasingOption.EaseInOutQuart); }
private void setData() { RealmResults<RealmDemoData> result = mRealm.where(RealmDemoData.class).findAll(); //RealmBarDataSet<RealmDemoData> set = new RealmBarDataSet<RealmDemoData>(result, "stackValues", "xIndex"); // normal entries RealmRadarDataSet<RealmDemoData> set = new RealmRadarDataSet<RealmDemoData>(result, "yValue"); // stacked entries set.setLabel("Realm RadarDataSet"); set.setDrawFilled(true); set.setColor(ColorTemplate.rgb("#009688")); set.setFillColor(ColorTemplate.rgb("#009688")); set.setFillAlpha(130); set.setLineWidth(2f); ArrayList<IRadarDataSet> dataSets = new ArrayList<IRadarDataSet>(); dataSets.add(set); // add the dataset // create a data object with the dataset list RadarData data = new RadarData(dataSets); styleData(data); // set data mChart.setData(data); mChart.animateY(1400); }
public void btn_logout_click(View v) { RealmConfiguration config = new RealmConfiguration.Builder().name("yyox.realm").build(); Realm objRealm = Realm.getInstance(config); //查找 RealmUser realmUser = objRealm.where(RealmUser.class).findFirst(); if (realmUser != null) { //先删除 objRealm.beginTransaction(); RealmResults results = objRealm.where(RealmUser.class).findAll(); results.deleteAllFromRealm(); objRealm.commitTransaction(); } mPresenter.requestLogout(this); WEApplication weApplication = (WEApplication) getApplication(); weApplication.setRealmUser(null); Intent intent = new Intent(); setResult(CodeDefine.SETTING_RESULT, intent); }
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_history); // Calling the RecyclerView mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view); mRecyclerView.setHasFixedSize(true); Realm.init(this); realm = Realm.getDefaultInstance(); RealmResults<StepCounts> results = realm.where(StepCounts.class).findAll(); // The number of Columns mLayoutManager = new GridLayoutManager(this, 1); mRecyclerView.setLayoutManager(mLayoutManager); mAdapter = new HistoryAdapter(results,HistoryActivity.this); mRecyclerView.setAdapter(mAdapter); }
private Observable<List<Task>> createResults(QuerySelector<DbTask> querySelector) { return Observable.create((ObservableOnSubscribe<List<Task>>) emitter -> { Realm realm = Realm.getDefaultInstance(); final RealmResults<DbTask> dbTasks = querySelector.createQuery(realm); final RealmChangeListener<RealmResults<DbTask>> realmChangeListener = element -> { if(element.isLoaded() && !emitter.isDisposed()) { List<Task> tasks = mapFrom(element); if(!emitter.isDisposed()) { emitter.onNext(tasks); } } }; emitter.setDisposable(Disposables.fromAction(() -> { if(dbTasks.isValid()) { dbTasks.removeChangeListener(realmChangeListener); } realm.close(); })); dbTasks.addChangeListener(realmChangeListener); }).subscribeOn(looperScheduler.getScheduler()).unsubscribeOn(looperScheduler.getScheduler()); }
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.layout_recycler_view, container, false); unbinder = ButterKnife.bind(this, rootView); Bundle arguments = getArguments(); int infoType = arguments.getInt(ARG_INFO_TYPE); Realm realm = Realm.getDefaultInstance(); Timber.d("type:%s", infoType); RealmResults<TemplateItem> results = realm.where(TemplateItem.class) .beginsWith("template.type.id", String.valueOf(infoType)) .findAllSorted("id"); mAdapter = new TemplatesAdapter(getContext(), results, false, false); recyclerView.setAdapter(mAdapter); recyclerView.setLayoutManager(new LinearLayoutManager(getContext())); return rootView; }
/** * Loads the news feed as well as all future updates. */ @UiThread public Flowable<RealmResults<NYTimesStory>> loadNewsFeed(@NonNull String sectionKey, boolean forceReload) { // Start loading data from the network if needed // It will put all data into Realm if (forceReload || timeSinceLastNetworkRequest(sectionKey) > MINIMUM_NETWORK_WAIT_SEC) { dataLoader.loadData(sectionKey, apiKey, realm, networkLoading); lastNetworkRequest.put(sectionKey, System.currentTimeMillis()); } // Return the data in Realm. The query result will be automatically updated when the network requests // save data in Realm return realm.where(NYTimesStory.class) .equalTo(NYTimesStory.API_SECTION, sectionKey) .findAllSortedAsync(NYTimesStory.PUBLISHED_DATE, Sort.DESCENDING) .asFlowable(); }
private void saveData(List<IOS> data) {//刷新时才调用到 RealmResults<IOS> all = mRealm.where(IOS.class).findAll(); if (all.size() > 0) { IOS ios = all.get(0); if (ios != null) { if (!(ios.content).equals(data.get(0).content)) { mRealm.executeTransaction(realm -> { items.clear(); time2 = ""; realm.delete(IOS.class); realm.copyToRealmOrUpdate(data); }); } else {//数据一样不保存,同时不做 Adapter 刷新 mPage = mPageIndex; AppUtils.toast(R.string.tip_no_new_data); mView.hideLoading(); } } } else { mRealm.executeTransaction(realm -> realm.copyToRealmOrUpdate(data)); } }
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_schedule, container, false); int day = getArguments().getInt(ARG_SECTION_NUMBER); InstinctsApplication instinctsApplication = (InstinctsApplication) getActivity().getApplication(); RealmHelper realmHelper = instinctsApplication.getRealmHelper(); Realm realm = realmHelper.getRealmInstance(); RealmResults<Event> eventRealmResults = realm.where(Event.class) .contains("startTime", (day > 9) ? day + "-03-2017" : "0" + day + "-03-2017") .findAllSorted("startTime"); ScheduleAdapter adapter = new ScheduleAdapter(getActivity(), eventRealmResults); RecyclerView eventsRecyclerView = (RecyclerView) rootView.findViewById(R.id.events_recycler_view); eventsRecyclerView.setAdapter(adapter); eventsRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity())); return rootView; }
@Override public void init() { RealmResults<TodoList> listResults = todoRepository.queryList(listId); list = listResults.get(0); view.initViews(list.getTitle()); bindData(); list.addChangeListener(new RealmChangeListener<RealmModel>() { @Override public void onChange(RealmModel element) { if (view != null) { bindData(); view.notifyDataChanged(list.getTitle()); } } }); }
@Override public void init(long taskId) { RealmResults<Task> taskResults = repository.queryTask(taskId); if (taskResults.size() > 0) { task = taskResults.get(0); } task.addChangeListener(new RealmChangeListener<RealmModel>() { @Override public void onChange(RealmModel element) { task.getId(); view.updateViews(task); } }); view.initViews(); view.updateViews(task); }
@NonNull private RealmResults<Post> getPosts() { switch (POSTS) { case POSTS_ACTIVE: { return PostRepository.getActive(); } case POSTS_ARCHIVED: { return PostRepository.getArchived(); } case POSTS_PACKAGES: { return PostRepository.getByCategory(CATEGORY_PACKAGES); } case POSTS_TUTORIALS: { return PostRepository.getByCategory(CATEGORY_TUTORIALS); } case POSTS_FAVOURITES: { return PostRepository.getFavourites(); } default: { return PostRepository.getActive(); } } }
public MarketAdapter(Context context, RealmResults<Currency>conversions) { try { this.context = context; layoutInflater = LayoutInflater.from(context); this.conversions=conversions; } catch (Exception e) { e.printStackTrace(); } }
private RealmResults<T> applySortingMode(SortingMode sm, RealmQuery<T> query){ KeysAndSorts keysAndSorts = convertSortingMode(sm); if(keysAndSorts != null){ return query.findAllSortedAsync(keysAndSorts.key, keysAndSorts.sort); } return query.findAll(); }
/** * save contacts data into local storage * @param contacts */ public static void saveContacts(final RealmList<RealmContact> contacts ){ Realm realm = Realm.getDefaultInstance(); realm.beginTransaction(); final RealmResults<RealmContact> results = realm.where(RealmContact.class).findAll(); results.deleteAllFromRealm(); realm.copyToRealmOrUpdate(contacts); realm.commitTransaction(); }
public <T extends RealmObject> void deleteAll(Class<T> clazz) { final RealmResults results = mRealm.where(clazz).findAll(); mRealm.executeTransaction(new Realm.Transaction() { @Override public void execute(Realm realm) { results.deleteAllFromRealm(); } }); }
@Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); moneys.addChangeListener(new RealmChangeListener<RealmResults<Currency>>() { @Override public void onChange(RealmResults<Currency> currencies) { setValue(); } }); }
@Override public void unlikeWeChatArticle(final String articleUrl) { mRealm.executeTransactionAsync(new Realm.Transaction() { @Override public void execute(Realm realm) { RealmResults<LikeArticleBean> results = realm.where(LikeArticleBean.class) .equalTo(LikeArticleFieldMap.ARTICLEURL, articleUrl).findAll(); if (results != null && !results.isEmpty() && results.isValid()) { results.deleteAllFromRealm(); } } }); }
@Override public Single<TokenInfo[]> fetch(NetworkInfo networkInfo, Wallet wallet) { return Single.fromCallable(() -> { Realm realm = null; try { realm = getRealmInstance(networkInfo, wallet); RealmResults<RealmTokenInfo> realmItems = realm.where(RealmTokenInfo.class) .sort("addedTime", Sort.ASCENDING) .findAll(); int len = realmItems.size(); TokenInfo[] result = new TokenInfo[len]; for (int i = 0; i < len; i++) { RealmTokenInfo realmItem = realmItems.get(i); if (realmItem != null) { result[i] = new TokenInfo( realmItem.getAddress(), realmItem.getName(), realmItem.getSymbol(), realmItem.getDecimals()); } } return result; } finally { if (realm != null) { realm.close(); } } }); }
@Override public void unlikeZhiHuColumnArticle(final int articleId) { mRealm.executeTransactionAsync(new Realm.Transaction() { @Override public void execute(Realm realm) { RealmResults<LikeArticleBean> results = realm.where(LikeArticleBean.class) .equalTo(LikeArticleFieldMap.ID, articleId).findAll(); if (results != null && !results.isEmpty() && results.isValid()) { results.deleteAllFromRealm(); } } }); }
private void basicLinkQuery(Realm realm) { showStatus("\nPerforming basic Link Query operation..."); showStatus("Number of persons: " + realm.where(Person.class).count()); RealmResults<Person> results = realm.where(Person.class).equalTo("cats.name", "Tiger").findAll(); showStatus("Size of result set: " + results.size()); }
private String complexQuery() { String status = "\n\nPerforming complex Query operation..."; Realm realm = Realm.getDefaultInstance(); status += "\nNumber of persons: " + realm.where(Person.class).count(); // Find all persons where age between 7 and 9 and name begins with "Person". RealmResults<Person> results = realm.where(Person.class) .between("age", 7, 9) // Notice implicit "and" operation .beginsWith("name", "Person").findAll(); status += "\nSize of result set: " + results.size(); realm.close(); return status; }
private void updateAdapter() { RealmResults<Note> results = realm.where(Note.class).findAll(); myDataSet.clear(); myDataSet.addAll(results); mAdapter.setListNote(myDataSet); mAdapter.notifyDataSetChanged(); }
@Test @RunTestInLooperThread @RunTestWithRemoteService(remoteService = SimpleCommitRemoteService.class, onLooperThread = true) public void expectSimpleCommit() { looperThread.runAfterTest(remoteService.afterRunnable); remoteService.createHandler(Looper.myLooper()); final SyncUser user = UserFactory.getInstance().createDefaultUser(Constants.AUTH_URL); String realmUrl = Constants.SYNC_SERVER_URL; final SyncConfiguration syncConfig = new SyncConfiguration.Builder(user,realmUrl) .directory(looperThread.getRoot()) .build(); final Realm realm = Realm.getInstance(syncConfig); final RealmResults<ProcessInfo> all = realm.where(ProcessInfo.class).findAll(); looperThread.keepStrongReference(all); all.addChangeListener(new RealmChangeListener<RealmResults<ProcessInfo>>() { @Override public void onChange(RealmResults<ProcessInfo> element) { assertEquals(1, all.size()); assertEquals("Background_Process1", all.get(0).getName()); realm.close(); user.logout(); remoteService.triggerServiceStep(SimpleCommitRemoteService.stepB_closeRealmAndLogOut); looperThread.testComplete(); } }); remoteService.triggerServiceStep(SimpleCommitRemoteService.stepA_openRealmAndCreateOneObject); }
@Override public Completable deleteAlarm(final Alarm alarm) { return Completable.create( new CompletableOnSubscribe() { @Override public void subscribe(final CompletableEmitter e) throws Exception { Realm realm = Realm.getDefaultInstance(); realm.beginTransaction(); RealmQuery<RealmAlarm> query = realm.where(RealmAlarm.class); query.equalTo("alarmId", alarm.getAlarmId()); RealmResults<RealmAlarm> result = query.findAll(); if (result.size() == 0) { realm.cancelTransaction(); e.onError(new Exception()); } else { result.deleteFromRealm(0); realm.commitTransaction(); e.onComplete(); } } } ); }
@Override public List<Note> getAll() { Realm realm = Realm.getInstance(configuration); RealmResults<NoteDAO> noteDAOs = realm.where(NoteDAO.class).findAll(); List<Note> notes = new ArrayList<>(noteDAOs.size()); for (NoteDAO dao : noteDAOs) { notes.add(RealmConverter.convert(dao)); } realm.close(); return notes; }
@Subscribe public void onLoadTagsEvent(LoadTagsEvent event) { RealmResults<Tag> tags = mRealm.where(Tag.class).findAllSorted("name"); List<Tag> tagsCopy = new ArrayList<>(tags.size()); for (Tag tag : tags) { tagsCopy.add(new Tag(tag.getName())); } getBus().post(new TagsLoadedEvent(tagsCopy)); }
public static <T extends RealmObject> Single<List<T>> getList(final Func1<Realm, RealmResults<T>> query) { return Single.fromEmitter(emitter -> { final Realm realm = Realm.getDefaultInstance(); final RealmResults<T> realmResults = query.call(realm); emitter.onSuccess(realm.copyFromRealm(realmResults)); emitter.setCancellation(realm::close); }); }
@Override public Flowable<List<Alarm>> getAlarms() { return Flowable.create( new FlowableOnSubscribe<List<Alarm>>() { @Override public void subscribe(FlowableEmitter<List<Alarm>> e) throws Exception { Realm realm = Realm.getDefaultInstance(); RealmQuery<RealmAlarm> query = realm.where(RealmAlarm.class); RealmResults<RealmAlarm> result = query.findAll(); List<Alarm> alarmList = new ArrayList<>(); if (result.size() == 0) { e.onComplete(); } else { for (int i = 0; i < result.size(); i++) { Alarm alarm = new Alarm(); RealmAlarm realmAlarm = result.get(i); alarm.setActive(realmAlarm.isActive()); alarm.setRenewAutomatically(realmAlarm.isRenewAutomatically()); alarm.setVibrateOnly(realmAlarm.isVibrateOnly()); alarm.setHourOfDay(realmAlarm.getHourOfDay()); alarm.setMinute(realmAlarm.getMinute()); alarm.setAlarmTitle(realmAlarm.getAlarmTitle()); alarm.setAlarmId(realmAlarm.getAlarmId()); alarmList.add( alarm ); } e.onNext(alarmList); } } }, BackpressureStrategy.LATEST); }
public RealmResults<RMatch> getMatches() { return realm.where(RMatch.class) .notEqualTo(RMatchFieldNames.SYNC_STATUS_VALUE, SyncStatus.DELETED.getId()) .notEqualTo(RMatchFieldNames.MATCH_STATE_VALUE, MatchState.EXPIRED.getNetworkValue()) .notEqualTo(RMatchFieldNames.MATCH_STATE_VALUE, MatchState.REJECT_SENT.getNetworkValue()) .findAllSorted(new String[] { RMatchFieldNames.SORT_WEIGHT, RMatchFieldNames.SCORE, RMatchFieldNames.EXPIRATION_DATE }, new Sort[] { Sort.DESCENDING, Sort.DESCENDING, Sort.ASCENDING }); }
@SuppressWarnings("NewApi") public Single<Optional<Task>> findTask(String taskId) { return Single.fromCallable((Callable<Optional<Task>>) () -> { try(Realm realm = Realm.getDefaultInstance()) { RealmResults<DbTask> tasks = realm.where(DbTask.class) .equalTo(DbTaskFields.ID, taskId) .findAll(); if(tasks.size() > 0) { return Optional.of(taskMapper.fromRealm(tasks.get(0))); } else { return Optional.absent(); } } }).subscribeOn(looperScheduler.getScheduler()); }
@Override public void init() { view.initViews(); listsResults = repository.getAllLists(); useFirstListAsDefault(); listsResults.addChangeListener(new RealmChangeListener<RealmResults<TodoList>>() { @Override public void onChange(RealmResults<TodoList> element) { if (view != null) { useFirstListAsDefault(); } } }); }
@Override public void unlikeGankArticle(final String articleUrl) { mRealm.executeTransactionAsync(new Realm.Transaction() { @Override public void execute(Realm realm) { RealmResults<LikeArticleBean> results = realm.where(LikeArticleBean.class) .equalTo(LikeArticleFieldMap.ARTICLEURL, articleUrl).findAll(); if (results != null && !results.isEmpty() && results.isValid()) { results.deleteAllFromRealm(); } } }); }
@Override public Flowable<Alarm> getAlarmsById(final String reminderId) { return Flowable.create( new FlowableOnSubscribe<Alarm>() { @Override public void subscribe(FlowableEmitter<Alarm> e) throws Exception { Realm realm = Realm.getDefaultInstance(); RealmQuery<RealmAlarm> query = realm.where(RealmAlarm.class); query.equalTo("alarmId", reminderId); RealmResults<RealmAlarm> result = query.findAll(); if (result.size() == 0) { e.onError(new Exception("AlarmNotFoundException")); } else { RealmAlarm realmAlarm = result.get(0); Alarm alarm = new Alarm(); alarm.setAlarmId(realmAlarm.getAlarmId()); alarm.setActive(realmAlarm.isActive()); alarm.setRenewAutomatically(realmAlarm.isRenewAutomatically()); alarm.setVibrateOnly(realmAlarm.isVibrateOnly()); alarm.setHourOfDay(realmAlarm.getHourOfDay()); alarm.setMinute(realmAlarm.getMinute()); alarm.setAlarmTitle(realmAlarm.getAlarmTitle()); e.onNext(alarm); } } }, BackpressureStrategy.LATEST); }
private void parseTestData() { // open empty processed data realm for use in parsing data Realm.deleteRealm(realmConfigProcessedData); realmProcessedData = Realm.getInstance(realmConfigProcessedData); // get all raw data RealmResults<RawTagData> rawTags = realmRawData.where(RawTagData.class).findAllSorted(RawTagData.DATE, Sort.ASCENDING); // reduce data set to just the raw data of the most recent sensor String tagId = rawTags.last().getTagId(); rawTags = rawTags.where().equalTo(RawTagData.TAG_ID, tagId).findAllSorted(RawTagData.DATE, Sort.ASCENDING); // reduce data set further to only MAX_READINGS_TO_TEST sensor readings for (int i = 0; i < min(MAX_READINGS_TO_TEST, rawTags.size()); i++) { addDataIfValid(rawTags.get(i)); } /* // add oldest readings of sensor for (int i = 0; i < min(MAX_READINGS_TO_TEST / 2, rawTags.size() / 2); i++) { addDataIfValid(rawTags.get(i)); } // add newest readings of sensor for (int i = max(rawTags.size() / 2, rawTags.size() - 1 - MAX_READINGS_TO_TEST / 2); i < rawTags.size() - 1; i++) { addDataIfValid(rawTags.get(i)); } */ assertThat(realmRawData.isEmpty(), is(false)); assertThat(readingDataList.size(), greaterThan(0)); }
@Override public void unlikeZhiHuNews(final int articleId) { mRealm.executeTransactionAsync(new Realm.Transaction() { @Override public void execute(Realm realm) { RealmResults<LikeArticleBean> results = realm.where(LikeArticleBean.class) .equalTo(LikeArticleFieldMap.ID, articleId).findAll(); if (results != null && !results.isEmpty() && results.isValid()) { results.deleteAllFromRealm(); } } }); }