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

The following examples show how to use io.realm.RealmResults#get() . 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: SiberiRealmDB.java    From siberi-android with MIT License 6 votes vote down vote up
@Override
public ExperimentContent select(String testName) {
    realm = Realm.getInstance(configuration);
    try {
        RealmResults<ExperimentObject> results = realm.where(ExperimentObject.class).equalTo("testName", testName).findAll();
        if (results.size() > 0) {
            ExperimentObject experimentObject = results.get(0);
            ExperimentContent experimentContent = new ExperimentContent(testName);
            experimentContent.setVariant(experimentObject.getVariant());
            try {
                experimentContent.setMetaData(new JSONObject(experimentObject.getMetaData()));
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return experimentContent;
        } else {
            return null;
        }
    } finally {
        realm.close();
    }
}
 
Example 2
Source File: HomeFragment.java    From citrus with Apache License 2.0 6 votes vote down vote up
private void onDismissedBySwipe(int[] reverseSortedPositions, RealmResults<Task> uncompletedTasks) {
    for (final int position : reverseSortedPositions) {
        final Task task = uncompletedTasks.get(position);
        TaskRepository.updateByCompleted(mUIThreadRealm, task, true);
        mHomeTaskListAdapter.notifyItemRemoved(position);
        showSnackbarWhenDismiss(getString(R.string.complete_task, task.getName()),
                new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        TaskRepository
                                .updateByCompleted(mUIThreadRealm, task, false);
                        mHomeTaskListAdapter.notifyItemInserted(position);
                        updateHomeTaskListAdapter();
                    }
                });
    }
    updateHomeTaskListAdapter();
}
 
Example 3
Source File: RealmRoomMessage.java    From iGap-Android with GNU Affero General Public License v3.0 5 votes vote down vote up
public static long findCustomMessageId(long roomId, EnumCustomMessageId customMessageId, int count) {
    long messageId = 0;
    Realm realm = Realm.getDefaultInstance();
    if (customMessageId == EnumCustomMessageId.FROM_BEGIN) {
        messageId = 0;
    } else if (customMessageId == EnumCustomMessageId.FROM_NOW) {
        RealmRoomMessage realmRoomMessage = RealmRoomMessage.findLastMessage(realm, roomId);
        if (realmRoomMessage != null) {
            messageId = realmRoomMessage.getMessageId();
        } else {
            messageId = 0;
        }
    } else {
        if (count > 0) {
            RealmResults<RealmRoomMessage> realmRoomMessages = RealmRoomMessage.findDescending(realm, roomId);
            if (realmRoomMessages.size() <= count) {
                messageId = 0;
            } else {
                RealmRoomMessage message = realmRoomMessages.get(count);
                if (message != null) {
                    messageId = message.getMessageId();
                }
            }
        }
    }
    realm.close();
    return messageId;
}
 
Example 4
Source File: PumpHistoryMisc.java    From 600SeriesAndroidUploader with MIT License 5 votes vote down vote up
private static void calcLifetimes(PumpHistorySender pumpHistorySender, Realm realm, long pumpMAC, RECORDTYPE recordtype) {

        // lifetime for items
        RealmResults<PumpHistoryMisc> realmResults = realm.where(PumpHistoryMisc.class)
                .equalTo("pumpMAC", pumpMAC)
                .equalTo("recordtype", recordtype.value())
                .sort("eventDate", Sort.DESCENDING)
                .findAll();

        if (realmResults.size() > 1) {

            for (int i = 1; i < realmResults.size(); i++) {

                long lifetime = (realmResults.get(i - 1).eventDate.getTime() - realmResults.get(i).eventDate.getTime()) / 60000L;

                byte days = (byte) (lifetime / 1440);
                byte hours = (byte) ((lifetime % 1440) / 60);

                for (int lt = 0; lt < LIFETIMES_TOTAL && i - lt >= 0; lt++) {
                    byte[] lifetimes = realmResults.get(i - lt).lifetimes;

                    if (lifetimes[lt << 1] != days || lifetimes[(lt << 1) + 1] != hours) {
                        lifetimes[lt << 1] = days;
                        lifetimes[(lt << 1) + 1] = hours;
                        realmResults.get(i - lt).lifetimes = lifetimes;
                        pumpHistorySender.setSenderREQ(realmResults.get(i - lt));
                    }
                }

            }
        }
    }
 
Example 5
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 6
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 7
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 8
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 9
Source File: Image.java    From GankApp with GNU General Public License v2.0 5 votes vote down vote up
public static Image queryFirstZeroImg(Realm realm){
    RealmResults<Image> results =  realm.where(Image.class).equalTo("width",0)
            .findAllSorted("position", Sort.DESCENDING);
    if(results.size() > 0){
        Image image = results.get(0);
        return image;
    }
    return null;
}
 
Example 10
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 11
Source File: FragmentShearedMedia.java    From iGap-Android with GNU Affero General Public License v3.0 4 votes vote down vote up
private ArrayList<StructShearedMedia> addTimeToList(RealmResults<RealmRoomMessage> list) {

        ArrayList<StructShearedMedia> result = new ArrayList<>();

        String firstItemTime = "";
        String secondItemTime = "";
        SimpleDateFormat month_date = new SimpleDateFormat("yyyy/MM/dd");

        int isTimeHijri = HelperCalander.isTimeHijri();

        for (int i = 0; i < list.size(); i++) {

            Long time = list.get(i).getUpdateTime();
            secondItemTime = month_date.format(time);
            if (secondItemTime.compareTo(firstItemTime) > 0 || secondItemTime.compareTo(firstItemTime) < 0) {

                StructShearedMedia timeItem = new StructShearedMedia();

                if (isTimeHijri == 1) {
                    timeItem.messageTime = HelperCalander.getPersianCalander(time);
                } else if (isTimeHijri == 2) {
                    timeItem.messageTime = HelperCalander.getArabicCalander(time);
                } else {
                    timeItem.messageTime = secondItemTime;
                }

                timeItem.isItemTime = true;

                result.add(timeItem);

                firstItemTime = secondItemTime;
            }

            StructShearedMedia _item = new StructShearedMedia();
            _item.item = list.get(i);
            _item.messageId = list.get(i).getMessageId();

            result.add(_item);
        }

        return result;
    }
 
Example 12
Source File: PumpHistoryBG.java    From 600SeriesAndroidUploader with MIT License 4 votes vote down vote up
public static void calibration(
        PumpHistorySender pumpHistorySender, Realm realm, long pumpMAC,
        Date eventDate, int eventRTC, int eventOFFSET,
        double calFactor,
        int bgTarget) {

    // failed calibration
    if (calFactor == 0) return;

    PumpHistoryBG record = realm.where(PumpHistoryBG.class)
            .equalTo("pumpMAC", pumpMAC)
            .equalTo("calibrationRTC", eventRTC)
            .findFirst();
    if (record == null) {
        // look for a bg
        record = realm.where(PumpHistoryBG.class)
                .equalTo("pumpMAC", pumpMAC)
                .greaterThan("bgRTC", HistoryUtils.offsetRTC(eventRTC, - 20 * 60))
                .lessThanOrEqualTo("bgRTC", eventRTC)
                .equalTo("calibrationFlag", true)
                .equalTo("calibration", false)
                .findFirst();
        if (record == null) {
            Log.d(TAG, "*new*" + " calibration");
            record = realm.createObject(PumpHistoryBG.class);
            record.pumpMAC = pumpMAC;
            record.eventDate = eventDate;
        } else {
            Log.d(TAG, "*update*"  + " bg with calibration");
            if (record.entered) pumpHistorySender.setSenderREQ(record);
        }
        record.calibration = true;
        record.calibrationDate = eventDate;
        record.calibrationRTC = eventRTC;
        record.calibrationOFFSET = eventOFFSET;
        record.calibrationFactor = calFactor;
        record.calibrationTarget = bgTarget;

        // update calibrations for the sensor
        // find the sensor
        RealmResults<PumpHistoryMisc> results1 = realm.where(PumpHistoryMisc.class)
                .equalTo("pumpMAC", pumpMAC)
                .greaterThan("eventDate", new Date(eventDate.getTime() - 8 * 24 * 60 * 60000L))
                .lessThan("eventDate", eventDate)
                .equalTo("recordtype", PumpHistoryMisc.RECORDTYPE.CHANGE_SENSOR.value())
                .sort("eventDate", Sort.DESCENDING)
                .findAll();

        if (results1.size() > 0) {

            // find the sensor date range
            RealmResults<PumpHistoryMisc> results2 = realm.where(PumpHistoryMisc.class)
                    .equalTo("pumpMAC", pumpMAC)
                    .lessThan("eventDate", new Date(eventDate.getTime() + 8 * 24 * 60 * 60000L))
                    .greaterThan("eventDate", eventDate)
                    .equalTo("recordtype", PumpHistoryMisc.RECORDTYPE.CHANGE_SENSOR.value())
                    .sort("eventDate", Sort.ASCENDING)
                    .findAll();

            Date begin = results1.first().getEventDate();
            Date end = eventDate;

            if (results2.size() > 0)
                end = results2.first().getEventDate();

            // find all the calibrations for this sensor
            RealmResults<PumpHistoryBG> results3 = realm.where(PumpHistoryBG.class)
                    .equalTo("pumpMAC", pumpMAC)
                    .greaterThan("eventDate", begin)
                    .lessThan("eventDate", end)
                    .equalTo("calibration", true)
                    .sort("eventDate", Sort.ASCENDING)
                    .findAll();

            if (results3.size() > 0) {
                byte[] calibrations = new byte[results3.size()];
                for (int i = 0; i < results3.size(); i++) {
                    calibrations[i] = (byte) (results3.get(i).calibrationFactor * 10);
                }
                results1.first().setCalibrations(calibrations);
                pumpHistorySender.setSenderREQ(results1.first());
            }

        }

    }
}
 
Example 13
Source File: PerfTestRealm.java    From android-database-performance with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("ResultOfMethodCallIgnored")
@Override
protected void doBatchCrudRun(int count) throws Exception {
    final List<SimpleEntityNotNull> list = new ArrayList<>();
    for (int i = 0; i < count; i++) {
        list.add(SimpleEntityNotNullHelper.createEntity((long) i));
    }

    startClock();
    realm.beginTransaction();
    realm.insert(list);
    realm.commitTransaction();
    stopClock(Benchmark.Type.BATCH_CREATE);

    startClock();
    realm.beginTransaction();
    realm.insertOrUpdate(list);
    realm.commitTransaction();
    stopClock(Benchmark.Type.BATCH_UPDATE);

    startClock();
    RealmResults<SimpleEntityNotNull> reloaded = realm.where(SimpleEntityNotNull.class).findAll();
    stopClock(Benchmark.Type.BATCH_READ);

    // as Realm is not actually loading data, just referencing it,
    // at least make sure we access every property to force it being loaded
    startClock();
    for (int i = 0; i < reloaded.size(); i++) {
        SimpleEntityNotNull entity = reloaded.get(i);
        entity.getId();
        entity.getSimpleBoolean();
        entity.getSimpleByte();
        entity.getSimpleShort();
        entity.getSimpleInt();
        entity.getSimpleLong();
        entity.getSimpleFloat();
        entity.getSimpleDouble();
        entity.getSimpleString();
        entity.getSimpleByteArray();
    }
    stopClock(Benchmark.Type.BATCH_ACCESS);

    startClock();
    deleteAll();
    stopClock(Benchmark.Type.BATCH_DELETE);
}