io.realm.RealmResults Java Examples

The following examples show how to use io.realm.RealmResults. 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: RealmManager.java    From mangosta-android with Apache License 2.0 6 votes vote down vote up
public void hideAllChatsOfType(int type) {
    Realm realm = getRealm();

    RealmResults<Chat> chats = realm.where(Chat.class)
            .equalTo("type", type)
            .findAll();

    for (Chat chat : chats) {
        realm.beginTransaction();
        if (chat.isValid()) {
            chat.setShow(false);
        }
        realm.copyToRealmOrUpdate(chat);
        realm.commitTransaction();
    }

    realm.close();
}
 
Example #2
Source File: RealmDatabaseActivityScatter.java    From Stayfit with Apache License 2.0 6 votes vote down vote up
private void setData() {

        RealmResults<RealmDemoData> result = mRealm.allObjects(RealmDemoData.class);

        RealmScatterDataSet<RealmDemoData> set = new RealmScatterDataSet<RealmDemoData>(result, "value", "xIndex");
        set.setLabel("Realm ScatterDataSet");
        set.setScatterShapeSize(9f);
        set.setColor(ColorTemplate.rgb("#CDDC39"));
        set.setScatterShape(ScatterChart.ScatterShape.CIRCLE);

        ArrayList<IScatterDataSet> dataSets = new ArrayList<IScatterDataSet>();
        dataSets.add(set); // add the dataset

        // create a data object with the dataset list
        RealmScatterData data = new RealmScatterData(result, "xValue", dataSets);
        styleData(data);

        // set data
        mChart.setData(data);
        mChart.animateY(1400, Easing.EasingOption.EaseInOutQuart);
    }
 
Example #3
Source File: RealmBufferResolver.java    From TimberLorry with Apache License 2.0 6 votes vote down vote up
@Override
public List<Record> fetch() {
    List<Record> records = new ArrayList<>();
    Realm realm = null;
    try {
        realm = Realm.getInstance(realmConfig);
        RealmQuery<RecordObject> query = realm.where(RecordObject.class);
        RealmResults<RecordObject> results = query.findAll();
        for (RecordObject obj : results) {
            records.add(new Record(Utils.forName(obj.getClassName()), obj.getBody()));
        }
        return records;
    } finally {
        if (realm != null)
            realm.close();
    }
}
 
Example #4
Source File: NotificationRealm.java    From talk-android with MIT License 6 votes vote down vote up
public List<Notification> getAllNotificationWithCurrentThread() {
    List<Notification> notifications = new ArrayList<>();
    Realm realm = RealmProvider.getInstance();
    try {
        realm.beginTransaction();
        RealmResults<Notification> realmResults = realm
                .where(Notification.class)
                .equalTo(Notification.TEAM_ID, BizLogic.getTeamId())
                .findAll();
        for (Notification realmResult : realmResults) {
            Notification notification = new Notification();
            copy(notification, realmResult);
            copyObject(notification, realmResult);
            notifications.add(notification);
        }
        realm.commitTransaction();
    } catch (Exception e) {
        e.printStackTrace();
        realm.cancelTransaction();
    } finally {
        realm.close();
    }
    return notifications;
}
 
Example #5
Source File: DatabaseCurrencyDataSource.java    From exchange-rates-mvvm with Apache License 2.0 6 votes vote down vote up
@Override
public Observable<CurrencyData> getCurrencies(final Date date) {

    final long midnight = midnight(date.getTime());

    return readFromRealm((realm, emitter) -> {
        final RealmResults<ValueEntity> items = realm.where(ValueEntity.class)
                .equalTo(ValueEntity.TIMESTAMP, midnight)
                .findAll();
        if (items == null || items.size() == 0) {
            emitter.onComplete();
        }
        Map<String, Double> currencies = new HashMap<>();
        for (ValueEntity item : items) {
            currencies.put(item.getCode(), item.getValue());
        }
        emitter.onNext(new CurrencyData(new Date(midnight), currencies, ""));
        emitter.onComplete();
    });
}
 
Example #6
Source File: TransactionsRealmCache.java    From alpha-wallet-android with MIT License 6 votes vote down vote up
@Override
public Single<Transaction[]> fetchTransaction(Wallet wallet, int maxTransactions, List<Integer> networkFilters) {
       return Single.fromCallable(() -> {
           try (Realm instance = realmManager.getRealmInstance(wallet))
           {
               RealmResults<RealmTransaction> txs = instance.where(RealmTransaction.class)
                       .sort("timeStamp", Sort.DESCENDING)
                       .findAll();
               Log.d(TAG, "Found " + txs.size() + " TX Results");
               return convertCount(txs, maxTransactions, networkFilters);
           }
           catch (Exception e)
           {
               return new Transaction[0];
           }
       });
}
 
Example #7
Source File: FragmentNow.java    From StudentAttendanceCheck with MIT License 6 votes vote down vote up
private void realmUpdateModStatus(int targetingModule, RealmResults<StudentModuleDao> studentModuleDao, int status) {

        String modStatus = null;
        switch (status) {
            case STATUS_ACTIVE:
                modStatus = "active";
                break;
            case STATUS_INACTIVE:
                modStatus = "inactive";
                break;
            case STATUS_NO_MORE:
                modStatus = "no more class";
                break;
            default:
                break;
        }

        Realm realm = Realm.getDefaultInstance();
        realm.beginTransaction();
        realm.copyToRealmOrUpdate(studentModuleDao).get(targetingModule).setModStatus(modStatus);
        realm.commitTransaction();

    }
 
Example #8
Source File: FragmentNow.java    From StudentAttendanceCheck with MIT License 6 votes vote down vote up
private void showCurrentStatus(RealmResults<StudentModuleDao> studentModuleDao, int targetingModule) {

        b.moduleIdTxt.setVisibility(View.VISIBLE);
        b.moduleTimeTxt.setVisibility(View.VISIBLE);
        b.lecturerTxt.setVisibility(View.VISIBLE);
        b.locationTxt.setVisibility(View.VISIBLE);
        b.statusBtn.setVisibility(View.VISIBLE);
        b.statusTxt.setVisibility(View.VISIBLE);

        b.moduleNameTxt.setText(studentModuleDao.get(targetingModule).getName());
        b.moduleIdTxt.setText(studentModuleDao.get(targetingModule).getModuleId());

        SimpleDateFormat currentTimeFormat = new SimpleDateFormat("HH:mm");
        String timeStr = "From " + currentTimeFormat.format(studentModuleDao.get(targetingModule).getStartDate())
                + " to " + currentTimeFormat.format(studentModuleDao.get(targetingModule).getEndDate());

        b.moduleTimeTxt.setText(timeStr);
        b.lecturerTxt.setText("with " + studentModuleDao.get(targetingModule).getLecturer());
        b.locationTxt.setText("at " + studentModuleDao.get(targetingModule).getRoom());
        buttonStatusColorManager(targetingModule);

    }
 
Example #9
Source File: LocalChatBDRealmManager.java    From LazyRecyclerAdapter with MIT License 6 votes vote down vote up
private List<ChatBaseModel> resolveMessageList(RealmResults<ChatMessageModel> chatMessageModels) {
    List<ChatBaseModel> list = new ArrayList<>();
    for (ChatMessageModel chatMessage : chatMessageModels) {
        switch (chatMessage.getType()) {
            case ChatConst.TYPE_TEXT: {
                ChatTextModel chatText = new ChatTextModel();
                chatText.setContent(chatMessage.getContent());
                cloneChatBaseModel(chatText, chatMessage);
                list.add(chatText);
                break;
            }
            case ChatConst.TYPE_IMAGE: {
                ChatImageModel chatImg = new ChatImageModel();
                chatImg.setImgUrl(chatMessage.getContent());
                cloneChatBaseModel(chatImg, chatMessage);
                list.add(chatImg);
                break;
            }
        }
    }
    return list;
}
 
Example #10
Source File: PumpHistoryHandler.java    From 600SeriesAndroidUploader with MIT License 6 votes vote down vote up
public void reset() {
    historyRealm.executeTransaction(new Realm.Transaction() {
        @Override
        public void execute(@NonNull Realm realm) {

            int count = 0;
            for (DBitem dBitem : historyDB) {
                RealmResults<PumpHistoryInterface> records = dBitem.results.where().findAll();
                count += records.size();
                records.deleteAllFromRealm();
            }

            Log.d(TAG, "reset history database: deleted " + count + " history records");

            final RealmResults<HistorySegment> segment = historyRealm
                    .where(HistorySegment.class)
                    .findAll();
            segment.deleteAllFromRealm();

            Log.d(TAG, "reset history segments: deleted " + segment.size() + " segment records");
        }
    });
}
 
Example #11
Source File: RealmBarDataSet.java    From JNChartDemo with Apache License 2.0 5 votes vote down vote up
public RealmBarDataSet(RealmResults<T> results, String yValuesField, String xIndexField) {
    super(results, yValuesField, xIndexField);
    mHighLightColor = Color.rgb(0, 0, 0);

    build(this.results);
    calcMinMax(0, results.size());
}
 
Example #12
Source File: RealmCandleDataSet.java    From Stayfit with Apache License 2.0 5 votes vote down vote up
/**
 * Constructor for creating a LineDataSet with realm data.
 *
 * @param result     the queried results from the realm database
 * @param highField  the name of the field in your data object that represents the "high" value
 * @param lowField   the name of the field in your data object that represents the "low" value
 * @param openField  the name of the field in your data object that represents the "open" value
 * @param closeField the name of the field in your data object that represents the "close" value
 */
public RealmCandleDataSet(RealmResults<T> result, String highField, String lowField, String openField, String closeField) {
    super(result, null);
    this.mHighField = highField;
    this.mLowField = lowField;
    this.mOpenField = openField;
    this.mCloseField = closeField;

    build(this.results);
    calcMinMax(0, this.results.size());
}
 
Example #13
Source File: Integration.java    From HAPP with GNU General Public License v3.0 5 votes vote down vote up
public static Integration getIntegrationByID(String uuid, Realm realm) {
    RealmResults<Integration> results = realm.where(Integration.class)
            .equalTo("id", uuid)
            .findAllSorted("timestamp", Sort.DESCENDING);
    if (results.isEmpty()) {
        return null;
    } else {
        return results.first();
    }
}
 
Example #14
Source File: SundayFragment.java    From StudentAttendanceCheck with MIT License 5 votes vote down vote up
@SuppressWarnings("UnusedParameters")
    private void initInstances(View rootView, Bundle savedInstanceState) {
        // Init 'View' instance(s) with rootView.findViewById here
        // Note: State of variable initialized here could not be saved
        //       in onSavedInstanceState
        realm = Realm.getDefaultInstance();
        RealmResults<StudentModuleDao> studentModuleDao = realm.getDefaultInstance().where(StudentModuleDao.class).equalTo("day","Sun", Case.SENSITIVE).findAll();
        if (studentModuleDao.size()!=0) {

            LinearLayoutManager rvLayoutManager = new LinearLayoutManager(getContext());
            b.rvSundayTimeTable.setLayoutManager(rvLayoutManager);
            mTimeTableListAdapter = new TimeTableListAdapter(getContext(), studentModuleDao, true);
            b.rvSundayTimeTable.setAdapter(mTimeTableListAdapter);
            b.rvSundayTimeTable.setHasFixedSize(true);

        } else {

            b.rvSundayTimeTable.setVisibility(View.GONE);
            b.sunNoModuleText.setText("You are free today");
            b.sunNoModuleText.setVisibility(View.VISIBLE);

        }


//        connectToDataBase();

    }
 
Example #15
Source File: MessageRealm.java    From talk-android with MIT License 5 votes vote down vote up
public Observable<List<Message>> getLocalMessage(final String id, final String teamId, final String boundaryId, final long begin, final long end) {
    return Observable.create(new OnSubscribeRealm<List<Message>>() {
        @Override
        public List<Message> get(Realm realm) {
            RealmQuery<Message> query = realm.where(Message.class)
                    .equalTo(Message.FOREIGN_ID, id)
                    .equalTo(Message.TEAM_ID, teamId);
            if (begin != 0) {
                query.greaterThan(Message.CREATE_AT_TIME, begin);
                query.notEqualTo(Message.ID, boundaryId);
            }
            if (end != 0) {
                query.lessThan(Message.CREATE_AT_TIME, end);
                query.notEqualTo(Message.ID, boundaryId);
            }
            RealmResults<Message> realmResults = query.findAll();
            realmResults.sort(Message.CREATE_AT_TIME, Sort.ASCENDING);
            List<Message> messageList = new ArrayList<>(realmResults.size());
            for (Message message : realmResults) {
                Message msg = new Message();
                copy(msg, message);
                messageList.add(msg);
            }
            return messageList;
        }
    }).subscribeOn(Schedulers.io());
}
 
Example #16
Source File: HistoryPresenter.java    From ForPDA with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void getHistory() {
    if (realm.isClosed()) {
        return;
    }
    view.setRefreshing(true);
    RealmResults<HistoryItemBd> results = realm
            .where(HistoryItemBd.class)
            .findAllSorted("unixTime", Sort.DESCENDING);
    view.showHistory(results);
    view.setRefreshing(false);
}
 
Example #17
Source File: BaseRealmDaoTest.java    From mvvm-template with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void test_GetAll() throws Exception {
    List<TestModel> models = sampleModelList(20);
    RealmResults<TestModel> results = initFindAllSorted(query, models);

    assertThat(dao.getAll().getData(), is(results));
    assertThat(results.size(), is(20));
}
 
Example #18
Source File: TodayModule.java    From StudentAttendanceCheck with MIT License 5 votes vote down vote up
public RealmResults<StudentModuleDao> getTodayModule() {

        String weekDay = dayOfWeek();

        Realm realm = Realm.getDefaultInstance();
        RealmResults<StudentModuleDao> studentModuleDao = realm.getDefaultInstance()
                .where(StudentModuleDao.class)
                .equalTo("day",weekDay.trim(), Case.SENSITIVE).findAll();

        return studentModuleDao;
    }
 
Example #19
Source File: DatabaseManager.java    From Easy_xkcd with Apache License 2.0 5 votes vote down vote up
public void removeAllFavorites() {
    RealmResults<RealmComic> favorites = getFavComics();
    realm.beginTransaction();
    Timber.d("size : %d", favorites.size());
    while (favorites.size() != 0) {
        favorites.first().setFavorite(false);
        Timber.d("size : %d", favorites.size());
    }
    realm.commitTransaction();
}
 
Example #20
Source File: MainActivity.java    From journaldev with MIT License 5 votes vote down vote up
private void filterByAge() {
    mRealm.executeTransaction(new Realm.Transaction() {
        @Override
        public void execute(Realm realm) {

            RealmResults<Employee> results = realm.where(Employee.class).greaterThanOrEqualTo(Employee.PROPERTY_AGE, 25).findAllSortedAsync(Employee.PROPERTY_NAME);

            txtFilterByAge.setText("");
            for (Employee employee : results) {
                txtFilterByAge.append(employee.name + " age: " + employee.age + " skill: " + employee.skills.size());
            }
        }
    });
}
 
Example #21
Source File: Image.java    From GankApp with GNU General Public License v2.0 5 votes vote down vote up
public static Image queryImageByUrl(Realm realm,String objectId){
    RealmResults<Image> results =  realm.where(Image.class).equalTo("_id",objectId).findAll();
    if(results.size() > 0){
        Image image = results.get(0);
        return image;
    }
    return null;
}
 
Example #22
Source File: ChampionManager.java    From Theogony with MIT License 5 votes vote down vote up
public List<Champion> queryByKeyWord(String query) {
    Realm realm = RealmProvider.getInstance().getRealm();
    try {
        RealmResults<Champion> results = realm.where(Champion.class)
                .beginGroup()
                .contains("name", query)
                .or()
                .contains("title", query)
                .endGroup()
                .findAll();
        return realm.copyFromRealm(results);
    } finally {
        realm.close();
    }
}
 
Example #23
Source File: Monarchy.java    From realm-monarchy with Apache License 2.0 5 votes vote down vote up
<T extends RealmModel> void createAndObserveRealmQuery(final LiveResults<T> liveResults) {
    Realm realm = realmThreadLocal.get();
    checkRealmValid(realm);
    if(liveResults == null) {
        return;
    }
    RealmResults<T> results = liveResults.createQuery(realm);
    resultsRefs.get().put(liveResults, results);
    results.addChangeListener(new RealmChangeListener<RealmResults<T>>() {
        @Override
        public void onChange(@Nonnull RealmResults<T> realmResults) {
            liveResults.updateResults(realmResults);
        }
    });
}
 
Example #24
Source File: DatabaseRealm.java    From openwebnet-android with MIT License 5 votes vote down vote up
public <T extends RealmObject> List<T> findCopyWhere(Class<T> clazz, String field, Integer value, String orderBy) {
    RealmResults<T> results = query(clazz).equalTo(field, value).findAll();
    if (orderBy != null) {
        results.sort(orderBy, Sort.ASCENDING);
    }
    return getRealmInstance().copyFromRealm(results);
}
 
Example #25
Source File: StatisticsFragment.java    From batteryhub with Apache License 2.0 5 votes vote down vote up
/**
 * Queries the data from mDatabase.
 *
 * @param interval Time interval for fetching the data.
 */
private void loadData(final int interval) {
    long now = System.currentTimeMillis();
    RealmResults<BatteryUsage> results;

    mChartCards = new ArrayList<>();

    // Make sure mDatabase instance is opened
    if (mActivity.mDatabase.isClosed()) {
        mActivity.mDatabase.getDefaultInstance();
    }

    // Query results according to selected time interval
    if (interval == DateUtils.INTERVAL_24H) {
        results = mActivity.mDatabase.betweenUsages(
                DateUtils.getMilliSecondsInterval(DateUtils.INTERVAL_24H),
                now
        );
    } else if (interval == DateUtils.INTERVAL_3DAYS) {
        results = mActivity.mDatabase.betweenUsages(
                DateUtils.getMilliSecondsInterval(DateUtils.INTERVAL_3DAYS),
                now
        );
    } else if (interval == DateUtils.INTERVAL_5DAYS) {
        results = mActivity.mDatabase.betweenUsages(
                DateUtils.getMilliSecondsInterval(DateUtils.INTERVAL_5DAYS),
                now
        );
    } else {
        results = mActivity.mDatabase.betweenUsages(
                DateUtils.getMilliSecondsInterval(DateUtils.INTERVAL_24H),
                now
        );
    }

    fillData(results);

    setAdapter(mSelectedInterval);
}
 
Example #26
Source File: RealmLineDataSet.java    From Stayfit with Apache License 2.0 5 votes vote down vote up
/**
 * Constructor for creating a LineDataSet with realm data.
 *
 * @param result       the queried results from the realm database
 * @param yValuesField the name of the field in your data object that represents the y-value
 * @param xIndexField  the name of the field in your data object that represents the x-index
 */
public RealmLineDataSet(RealmResults<T> result, String yValuesField, String xIndexField) {
    super(result, yValuesField, xIndexField);
    mCircleColors = new ArrayList<Integer>();

    // default color
    mCircleColors.add(Color.rgb(140, 234, 255));

    build(this.results);
    calcMinMax(0, results.size());
}
 
Example #27
Source File: Bg.java    From HAPP with GNU General Public License v3.0 5 votes vote down vote up
public static List<Bg> latestSince(Date startTime, Realm realm) {
    RealmResults<Bg> results = realm.where(Bg.class)
            .greaterThanOrEqualTo("datetime", startTime)
            .findAllSorted("datetime", Sort.DESCENDING);

    return results;
    //return new Select()
    //        .from(Bg.class)
    //        .where("datetime >= " + df.format(startTime))
    //        .orderBy("datetime desc")
    //        .limit(number)
    //        .execute();
}
 
Example #28
Source File: PumpHistoryHandler.java    From 600SeriesAndroidUploader with MIT License 5 votes vote down vote up
public boolean isLoopActive() {
    long now = System.currentTimeMillis();

    RealmResults<PumpHistoryLoop> results = historyRealm
            .where(PumpHistoryLoop.class)
            .greaterThan("eventDate", new Date(now - 6 * 60 * 60000L))
            .sort("eventDate", Sort.DESCENDING)
            .findAll();

    return results.size() > 0
            && (PumpHistoryLoop.RECORDTYPE.MICROBOLUS.equals(results.first().getRecordtype())
            || PumpHistoryLoop.RECORDTYPE.TRANSITION_IN.equals(results.first().getRecordtype()));
}
 
Example #29
Source File: Bolus.java    From HAPP with GNU General Public License v3.0 5 votes vote down vote up
public static List<Bolus> getBolusList(Realm realm){
    RealmResults<Bolus> results = realm.where(Bolus.class)
            .findAllSorted("timestamp", Sort.DESCENDING);
    if (results.isEmpty()) {
        return null;
    } else {
        return results;
    }
}
 
Example #30
Source File: RealmBaseDataSet.java    From JNChartDemo with Apache License 2.0 5 votes vote down vote up
/**
 * Constructor that takes the realm RealmResults, sorts & stores them.
 *
 * @param results
 * @param yValuesField
 * @param xIndexField
 */
public RealmBaseDataSet(RealmResults<T> results, String yValuesField, String xIndexField) {
    this.results = results;
    this.mValuesField = yValuesField;
    this.mIndexField = xIndexField;
    this.mValues = new ArrayList<S>();

    if (mIndexField != null)
        this.results.sort(mIndexField, Sort.ASCENDING);
}