Java Code Examples for io.realm.RealmResults#size()

The following examples show how to use io.realm.RealmResults#size() . 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: FragmentShowMember.java    From iGap-Android with GNU Affero General Public License v3.0 6 votes vote down vote up
private void fillAdapter() {

        if (roomType == GROUP) {
            role = RealmGroupRoom.detectMineRole(mRoomID).toString();
        } else {
            role = RealmChannelRoom.detectMineRole(mRoomID).toString();
        }
        RealmResults<RealmMember> realmMembers = RealmMember.filterRole(mRoomID, roomType, selectedRole);

        if (realmMembers.size() > 0 && G.fragmentActivity != null) {
            mAdapter = new MemberAdapter(realmMembers, roomType, mMainRole, userID);
            mRecyclerView.setAdapter(mAdapter);

            //fastAdapter
            //mAdapter = new MemberAdapterA();
            //for (RealmMember member : mList) {
            //    mAdapter.add(new MemberItem(realmRoom.getType(), mMainRole, userID).setInfo(member).withIdentifier(member.getPeerId()));
            //}
        }
    }
 
Example 2
Source File: TeamRealm.java    From talk-android with MIT License 6 votes vote down vote up
public List<Team> getTeamWithCurrentThread() {
    final List<Team> teams = new ArrayList<>();
    Realm realm = RealmProvider.getInstance();
    try {
        realm.beginTransaction();
        RealmResults<Team> realmResults = realm.where(Team.class).findAll();
        for (int i = 0; i < realmResults.size(); i++) {
            Team teamInfo = new Team();
            copy(teamInfo, realmResults.get(i));
            teams.add(teamInfo);
        }
        realm.commitTransaction();
    } catch (Exception e) {
        e.printStackTrace();
        realm.cancelTransaction();
    } finally {
        realm.close();
    }
    return teams;
}
 
Example 3
Source File: WednesdayFragment.java    From StudentAttendanceCheck with MIT License 6 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","Wed", Case.SENSITIVE).findAll();
        if (studentModuleDao.size()!=0) {

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

        } else {

            b.rvWednesdayTimeTable.setVisibility(View.GONE);
            b.wedNoModuleText.setText("You are free today");
            b.wedNoModuleText.setVisibility(View.VISIBLE);

        }

//        connectToDataBase();

    }
 
Example 4
Source File: DatabaseManager.java    From Easy_xkcd with Apache License 2.0 5 votes vote down vote up
public void setComicsRead(boolean isRead) {
    getSharedPrefs().edit().putString(COMIC_READ, "").apply();
    realm.beginTransaction();
    RealmResults<RealmComic> comics = realm.where(RealmComic.class).findAll();
    for (int i = 0; i < comics.size(); i++) {
        RealmComic comic = comics.get(i);
        comic.setRead(isRead);
        realm.copyToRealmOrUpdate(comic);
    }
    realm.commitTransaction();
}
 
Example 5
Source File: UrchinService.java    From 600SeriesAndroidUploader with MIT License 5 votes vote down vote up
private String bg(long timeNow) {
    RealmResults<PumpHistoryBG> bgResults = historyRealm
            .where(PumpHistoryBG.class)
            .greaterThanOrEqualTo("eventDate", new Date(timeNow))
            .sort("eventDate", Sort.ASCENDING)
            .findAll();
    if (bgResults.size() > 0)
        return FormatKit.getInstance().formatAsGlucose(bgResults.last().getBg());
    return "";
}
 
Example 6
Source File: UrchinService.java    From 600SeriesAndroidUploader with MIT License 5 votes vote down vote up
private String basalState() {
    if (pumpStatusEvent != null && pumpStatusEvent.getEventDate().getTime() > timeNow - 12 * 60 * 60000L) {

        if (pumpStatusEvent.isSuspended()) {
            RealmResults<PumpHistoryBasal> suspend = historyRealm.where(PumpHistoryBasal.class)
                    .greaterThan("eventDate", new Date(timeNow - 12 * 60 * 60000L))
                    .equalTo("recordtype", PumpHistoryBasal.RECORDTYPE.SUSPEND.value())
                    .or()
                    .equalTo("recordtype", PumpHistoryBasal.RECORDTYPE.RESUME.value())
                    .sort("eventDate", Sort.DESCENDING)
                    .findAll();
            // check if most recent suspend is in history and show the start time
            if (suspend.size() > 0 && PumpHistoryBasal.RECORDTYPE.SUSPEND.equals(suspend.first().getRecordtype()))
                return String.format("%s%s%s",
                        FormatKit.getInstance().getString(R.string.urchin_watchface_Suspend),
                        styleConcatenate(),
                        styleTime(suspend.first().getEventDate().getTime()));

        } else if (pumpStatusEvent.isTempBasalActive()) {
            int minutes = pumpStatusEvent.getTempBasalMinutesRemaining();
            return String.format("%s%s%s",
                    FormatKit.getInstance().getString(R.string.urchin_watchface_Temp),
                    styleConcatenate(),
                    styleDuration(minutes));
        }
    }

    return "";
}
 
Example 7
Source File: StatusNotification.java    From 600SeriesAndroidUploader with MIT License 5 votes vote down vote up
private String cgm() {

        RealmResults<PumpStatusEvent> results = pumpStatusEventRealmResults.where()
                .greaterThan("eventDate", new Date(currentTime - 15 * 60000L))
                .equalTo("cgmActive", true)
                .sort("eventDate", Sort.DESCENDING)
                .findAll();

        if (results.size() > 0) {

            PumpHistoryParser.CGM_EXCEPTION cgmException;
            if (results.first().isCgmException())
                cgmException = PumpHistoryParser.CGM_EXCEPTION.convert(
                        pumpStatusEventRealmResults.first().getCgmExceptionType());
            else if (results.first().isCgmCalibrating())
                cgmException = PumpHistoryParser.CGM_EXCEPTION.SENSOR_CAL_PENDING;
            else
                cgmException = PumpHistoryParser.CGM_EXCEPTION.NA;

            switch (cgmException) {
                case NA:
                    return String.format(
                            FormatKit.getInstance().getString(R.string.notification__CAL_remainingtime),
                            FormatKit.getInstance().formatMinutesAsHM(results.first().getCalibrationDueMinutes()));
                case SENSOR_INIT:
                    return String.format(
                            FormatKit.getInstance().getString(R.string.notification__WARMUP_remainingtime),
                            FormatKit.getInstance().formatMinutesAsHM(results.first().getCalibrationDueMinutes()));
                default:
                    return String.format(
                            FormatKit.getInstance().getString(R.string.notification__CGM_EXCEPTION),
                            cgmException.string());
            }
        }

        return "";
    }
 
Example 8
Source File: PumpHistoryHandler.java    From 600SeriesAndroidUploader with MIT License 5 votes vote down vote up
private void logSegments(String logTAG, RealmResults<HistorySegment> segment) {
    for (int i = 0; i < segment.size(); i++) {
        Log.d(TAG, String.format("%s segment: %s/%s start: %s end: %s",
                logTAG,
                i + 1,
                segment.size(),
                dateFormatter.format(segment.get(i).getFromDate()),
                dateFormatter.format(segment.get(i).getToDate())
        ));
    }
}
 
Example 9
Source File: RealmUtility.java    From Loop with Apache License 2.0 5 votes vote down vote up
public static List<String> getSuggestions(String query) {
    List<String> suggestions = new ArrayList<>();

    Realm realm = Realm.getDefaultInstance();
    try {
        RealmResults<RealmSuggestion> realmResults
                = realm.where(RealmSuggestion.class)
                .contains("token", query)
                .findAll();

        realmResults = realmResults.sort("timestamp", Sort.DESCENDING);

        if (realmResults != null) {
            int size = (realmResults.size() > 5) ? 5 : realmResults.size();
            for (int i = 0; i < size; i++) {
                RealmSuggestion realmSuggestion = realmResults.get(i);
                if (realmSuggestion != null) {
                    String token = realmSuggestion.getToken();
                    if (!TextUtils.isEmpty(token)) {
                        suggestions.add(suggestions.size(), token);
                    }
                }
            }
        }
    } finally {
        realm.close();
    }

    return suggestions;
}
 
Example 10
Source File: Image.java    From GankApp with GNU General Public License v2.0 5 votes vote down vote up
public static Image queryImageById(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 11
Source File: TuesdayFragment.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","Tue", Case.SENSITIVE).findAll();

        if (studentModuleDao.size()!=0) {

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

        } else {

            b.rvTuesdayTimeTable.setVisibility(View.GONE);
            b.tueNoModuleText.setText("You are free today");
            b.tueNoModuleText.setVisibility(View.VISIBLE);

        }

//        connectToDataBase();

    }
 
Example 12
Source File: PumpHistoryHandler.java    From 600SeriesAndroidUploader with MIT License 5 votes vote down vote up
public long historyRecency() {
    RealmResults<HistorySegment> results = historyRealm
            .where(HistorySegment.class)
            .sort("toDate", Sort.DESCENDING)
            .findAll();
    return results.size() == 0 ? -1 : System.currentTimeMillis() - results.first().getToDate().getTime();
}
 
Example 13
Source File: AccountManager.java    From quill with MIT License 5 votes vote down vote up
public static void deleteBlog(@NonNull String blogUrl) {
    RealmResults<BlogMetadata> matchingBlogs = findAllBlogsMatchingUrl(blogUrl);
    if (matchingBlogs.isEmpty()) {
        throw new IllegalStateException("No blog found matching the URL: " + blogUrl);
    }
    // we don't allow adding more than 1 blog with the same URL, so this should never happen
    if (matchingBlogs.size() > 1) {
        throw new IllegalStateException("More than 1 blog found matching the URL: " + blogUrl);
    }

    // delete blog metadata before data because data without metadata is harmless, but vice-versa is not
    // keep a copy of the metadata around so we can delete the data Realm after this
    final Realm realm = Realm.getDefaultInstance();
    BlogMetadata blogToDelete = matchingBlogs.get(0);
    RealmConfiguration dataRealmToDelete = realm.copyFromRealm(blogToDelete).getDataRealmConfig();
    RealmUtils.executeTransaction(realm, r -> {
        RealmObject.deleteFromRealm(blogToDelete);
    });

    // delete blog data
    Realm.deleteRealm(dataRealmToDelete);

    // if the active blog was deleted, set the active blog to a different one
    if (blogUrl.equals(getActiveBlogUrl())) {
        List<BlogMetadata> allBlogs = getAllBlogs();
        if (!allBlogs.isEmpty()) {
            setActiveBlog(allBlogs.get(0).getBlogUrl());
        } else {
            setActiveBlog("");
        }
    }
}
 
Example 14
Source File: UrchinService.java    From 600SeriesAndroidUploader with MIT License 5 votes vote down vote up
private String estimate() {
    if (dataStore.isSysEnableEstimateSGV()) {
        RealmResults<PumpHistoryCGM> cgmResults = historyRealm
                .where(PumpHistoryCGM.class)
                .sort("eventDate", Sort.DESCENDING)
                .findAll();
        if (cgmResults.size() > 0 && cgmResults.first().isEstimate())
            return FormatKit.getInstance().getString(R.string.urchin_watchface_Estimate);
    }
    return "";
}
 
Example 15
Source File: NetworkService.java    From quill with MIT License 5 votes vote down vote up
@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));
}
 
Example 16
Source File: MedtronicCnlService.java    From 600SeriesAndroidUploader with MIT License 4 votes vote down vote up
private void validatePumpRecord(PumpStatusEvent pumpRecord, PumpInfo activePump) {
    if (pumpRecord.isCgmActive()) {

        // pump can send the previous sgv at the post poll period minute mark
        // this can be a precursor to a lost sensor, sometimes there is a delay in the current sgv being available
        // we flag this and attempt another poll after a short delay
        if (pumpRecord.getEventRTC() - pumpRecord.getCgmRTC() > (POLL_PERIOD_MS + 10000) / 1000) {
            pumpRecord.setCgmOldWhenNewExpected(true);
            statPoll.incPollCgmOld();
        }

        // flag a new sgv as valid disregarding sgv's from multiple readings within the same poll period
        else if (!pumpRecord.isCgmWarmUp() && pumpRecord.getSgv() > 0 &&
                activePump.getPumpHistory().where().equalTo("cgmRTC", pumpRecord.getCgmRTC()).findAll().size() == 0) {
            pumpRecord.setValidSGV(true);
        }
    }

    // no cgm reading contained in this status record
    else {
        statPoll.incPollCgmNA();

        // check if cgm is in use
        RealmResults<PumpStatusEvent> results = activePump.getPumpHistory()
                .where()
                .equalTo("cgmActive", true)
                .sort("eventDate", Sort.DESCENDING)
                .findAll();

        if (results.size() > 0) {
            long timespan = pumpRecord.getEventDate().getTime() - results.first().getCgmDate().getTime();
            pumpRecord.setCgmLastSeen(timespan);
            // flag as lost when within recent period
            if (timespan < 180 * 60000L)
                pumpRecord.setCgmLostSensor(true);
            // record single stat per newly lost cgm sensor
            if (activePump.getPumpHistory().sort("eventDate", Sort.ASCENDING).last().isCgmActive()) {
                statPoll.incPollCgmLost();
            }
        }
    }
}
 
Example 17
Source File: MainActivity.java    From nosey with Apache License 2.0 4 votes vote down vote up
private boolean isRealmEmpty() {
    RealmResults result = Realm.getInstance(this).where(SomeModelA.class).findAll();
    Log.d("isRealmEmpty", result.size()+"");
    return result.size() == 0;
}
 
Example 18
Source File: SearchFragment.java    From iGap-Android with GNU Affero General Public License v3.0 4 votes vote down vote up
private void fillMessages(String text) {

        int size = list.size();
        Realm realm = Realm.getDefaultInstance();

        final RealmResults<RealmRoomMessage> results = realm.where(RealmRoomMessage.class).contains(RealmRoomMessageFields.MESSAGE, text, Case.INSENSITIVE).equalTo(RealmRoomMessageFields.EDITED, false).isNotEmpty(RealmRoomMessageFields.MESSAGE).findAll();
        if (results != null && results.size() > 0) {
            addHeader(G.fragmentActivity.getResources().getString(R.string.messages));
            for (RealmRoomMessage roomMessage : results) {

                StructSearch item = new StructSearch();

                item.time = roomMessage.getUpdateTime();
                item.comment = roomMessage.getMessage();
                item.id = roomMessage.getRoomId();
                item.type = SearchType.message;
                item.messageId = roomMessage.getMessageId();

                RealmRoom realmRoom = realm.where(RealmRoom.class).equalTo(RealmRoomFields.ID, roomMessage.getRoomId()).findFirst();

                if (realmRoom != null) { // room exist
                    item.name = realmRoom.getTitle();
                    item.initials = realmRoom.getInitials();
                    item.color = realmRoom.getColor();
                    item.roomType = realmRoom.getType();
                    item.avatar = realmRoom.getAvatar();
                    if (realmRoom.getType() == ProtoGlobal.Room.Type.CHAT && realmRoom.getChatRoom() != null) {
                        item.idDetectAvatar = realmRoom.getChatRoom().getPeerId();
                    } else {

                        if (realmRoom.getType() == ProtoGlobal.Room.Type.GROUP && realmRoom.getGroupRoom() != null) {
                            item.userName = realmRoom.getGroupRoom().getUsername();

                        } else if (realmRoom.getType() == ProtoGlobal.Room.Type.CHANNEL && realmRoom.getChannelRoom() != null) {
                            item.userName = realmRoom.getChannelRoom().getUsername();

                        }

                        item.idDetectAvatar = realmRoom.getId();
                    }
                    list.add(item);
                }
            }
        }

//        if (size == list.size()) {
//            list.remove(size - 1);
//        }

        realm.close();
    }
 
Example 19
Source File: DatabaseManager.java    From Easy_xkcd with Apache License 2.0 4 votes vote down vote up
public void fixCache() {
    int[] comicsToFix = {76, 80, 104, 1037, 1054, 1137, 1193, 1608, 1663, 1350, 2175, 2185, 2202}; //When adding new comic fixes, don't forget to add the number here!
    ArrayList<RealmComic> comicFixes = new ArrayList<>();
    for (int i : comicsToFix) {
        comicFixes.add(getRealmComic(i));
    }

    realm.beginTransaction();

    for (RealmComic comic : comicFixes) {
        if (comic == null) { continue; }
        switch (comic.getComicNumber()) {
            case 76: comic.setUrl("https://i.imgur.com/h3fi2RV.jpg");
                break;
            case 80: comic.setUrl("https://i.imgur.com/lWmI1lB.jpg");
                break;
            case 104: comic.setUrl("https://i.imgur.com/dnCNfPo.jpg");
                break;
            case 1037: comic.setUrl("https://www.explainxkcd.com/wiki/images/f/ff/umwelt_the_void.jpg");
                break;
            case 1054: comic.setTitle("The Bacon");
                break;
            case 1137: comic.setTitle("RTL");
                break;
            case 1193: comic.setUrl("https://www.explainxkcd.com/wiki/images/0/0b/externalities.png");
                break;
            case 1350: comic.setUrl("https://www.explainxkcd.com/wiki/images/3/3d/lorenz.png");
                break;
            case 1608: comic.setUrl("https://www.explainxkcd.com/wiki/images/4/41/hoverboard.png");
                break;
            case 1663: comic.setUrl("https://explainxkcd.com/wiki/images/c/ce/garden.png");
                break;
            case 2175: comic.setAltText(new String("When Salvador DalĂ­ died, it took months to get all the flagpoles sufficiently melted.".getBytes(UTF_8)));
                break;
            case 2185:
                comic.setTitle("Cumulonimbus");
                comic.setAltText("The rarest of all clouds is the altocumulenticulostratonimbulocirruslenticulomammanoctilucent cloud, caused by an interaction between warm moist air, cool dry air, cold slippery air, cursed air, and a cloud of nanobots.");
                comic.setUrl("https://imgs.xkcd.com/comics/cumulonimbus_2x.png");
                break;
            case 2202: comic.setUrl("https://imgs.xkcd.com/comics/earth_like_exoplanet.png");
                break;
        }
    }

    realm.copyToRealmOrUpdate(comicFixes);

    RealmResults<RealmComic> httpComics = realm.where(RealmComic.class).contains("url", "http://").findAll();
    for (int i = 0; i < httpComics.size(); i++) {
        httpComics.get(i).setUrl(httpComics.get(i).getUrl().replace("http", "https"));
    }

    realm.copyToRealmOrUpdate(httpComics);

    realm.commitTransaction();
}
 
Example 20
Source File: UrchinService.java    From 600SeriesAndroidUploader with MIT License 4 votes vote down vote up
private String lastBolus() {
    RealmResults<PumpHistoryBolus> results = historyRealm.where(PumpHistoryBolus.class)
            .greaterThan("eventDate", new Date(timeNow - 12 * 60 * 60000L))
            .equalTo("programmed", true)
            .sort("eventDate", Sort.DESCENDING)
            .findAll();

    if (results.size() > 0) {
        Double insulin;
        String tag = "";

        if (PumpHistoryParser.BOLUS_TYPE.DUAL_WAVE.equals(results.first().getBolusType())) {
            if (dataStore.isUrchinBolusTags()) tag = FormatKit.getInstance().getString(R.string.urchin_watchface_Dual);
            if (results.first().isSquareDelivered())
                insulin = results.first().getNormalDeliveredAmount() + results.first().getSquareDeliveredAmount();
            else if (results.first().isNormalDelivered())
                insulin = results.first().getNormalDeliveredAmount() + results.first().getSquareProgrammedAmount();
            else
                insulin = results.first().getNormalProgrammedAmount() + results.first().getSquareProgrammedAmount();

        } else if (PumpHistoryParser.BOLUS_TYPE.SQUARE_WAVE.equals(results.first().getBolusType())) {
            if (dataStore.isUrchinBolusTags()) tag = FormatKit.getInstance().getString(R.string.urchin_watchface_Square);
            if (results.first().isSquareDelivered())
                insulin = results.first().getSquareDeliveredAmount();
            else
                insulin = results.first().getSquareProgrammedAmount();

        } else {
            if (results.first().isNormalDelivered())
                insulin =  results.first().getNormalDeliveredAmount();
            else
                insulin =  results.first().getNormalProgrammedAmount();
        }

        return String.format("%s%s%s%s%s",
                tag,
                FormatKit.getInstance().formatAsDecimal(insulin, 0, 1, RoundingMode.HALF_UP),
                styleUnits(),
                styleConcatenate(),
                styleTime(results.first().getProgrammedDate().getTime()));
    }

    return "";
}