io.realm.RealmModel Java Examples

The following examples show how to use io.realm.RealmModel. 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: Monarchy.java    From realm-monarchy with Apache License 2.0 6 votes vote down vote up
/**
 * Provides ability to synchronously fetch a mapped RealmResults.
 *
 * @param query Query
 * @param <T>   RealmObject type
 * @param <U>   the mapped type
 * @return the copied list
 */
public <T extends RealmModel, U> List<U> fetchAllMappedSync(final Query<T> query, final Mapper<U, T> mapper) {
    final AtomicReference<List<U>> ref = new AtomicReference<>();
    doWithRealm(new RealmBlock() {
        @Override
        public void doWithRealm(Realm realm) {
            RealmResults<T> results = query.createQuery(realm).findAll();
            List<U> list = new ArrayList<>(results.size());
            for(T t : results) {
                list.add(mapper.map(t));
            }
            ref.set(list);
        }
    });
    return Collections.unmodifiableList(ref.get());
}
 
Example #2
Source File: FragmentContactsProfileViewModel.java    From iGap-Android with GNU Affero General Public License v3.0 6 votes vote down vote up
public void onResume() {
    mRoom = getRealm().where(RealmRoom.class).equalTo(RealmRoomFields.ID, shearedId).findFirst();
    if (mRoom != null) {
        if (changeListener == null) {
            changeListener = new RealmChangeListener<RealmModel>() {
                @Override
                public void onChange(final RealmModel element) {
                    G.handler.post(new Runnable() {
                        @Override
                        public void run() {
                            if (!((RealmRoom) element).isValid()) {
                                return;
                            }

                            sharedMedia.set(((RealmRoom) element).getSharedMediaCount());
                        }
                    });
                }
            };
        }
        mRoom.addChangeListener(changeListener);
        changeListener.onChange(mRoom);
    } else {
        sharedMedia.set(context.getString(R.string.there_is_no_sheared_media));
    }
}
 
Example #3
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 #4
Source File: NetworkService.java    From quill with MIT License 5 votes vote down vote up
private <T extends RealmModel> void deleteModels(Iterable<T> realmObjects) {
    if (! realmObjects.iterator().hasNext()) {
        return;
    }
    RealmUtils.executeTransaction(mRealm, realm -> {
        for (T realmObject : realmObjects) {
            RealmObject.deleteFromRealm(realmObject);
        }
    });
}
 
Example #5
Source File: NetworkService.java    From quill with MIT License 5 votes vote down vote up
private <T extends RealmModel> List<T> createOrUpdateModel(Iterable<T> objects,
                                                           @Nullable Runnable afterTransaction) {
    if (! objects.iterator().hasNext()) {
        return Collections.emptyList();
    }
    return RealmUtils.executeTransaction(mRealm, realm -> {
        List<T> realmObjects = mRealm.copyToRealmOrUpdate(objects);
        if (afterTransaction != null) {
            afterTransaction.run();
        }
        return realmObjects;
    });
}
 
Example #6
Source File: NetworkService.java    From quill with MIT License 5 votes vote down vote up
private <T extends RealmModel> T createOrUpdateModel(T object,
                                                     @Nullable Runnable afterTransaction) {
    return RealmUtils.executeTransaction(mRealm, realm -> {
        T realmObject = mRealm.copyToRealmOrUpdate(object);
        if (afterTransaction != null) {
            afterTransaction.run();
        }
        return realmObject;
    });
}
 
Example #7
Source File: NetworkService.java    From quill with MIT License 5 votes vote down vote up
/**
 * Generates a temporary primary key until the actual id is generated by the server. <b>Be
 * careful when calling this in a loop, if you don't save the object before calling it again,
 * you'll get the same id twice!</b>
 */
@NonNull
private <T extends RealmModel> String getTempUniqueId(Class<T> clazz) {
    int tempId = Integer.MAX_VALUE;
    while (mRealm.where(clazz).equalTo("id", String.valueOf(tempId)).findAll().size() > 0) {
        --tempId;
    }
    return String.valueOf(tempId);
}
 
Example #8
Source File: FragmentGroupProfileViewModel.java    From iGap-Android with GNU Affero General Public License v3.0 5 votes vote down vote up
public void onResume() {

        mRoom = getRealm().where(RealmRoom.class).equalTo(RealmRoomFields.ID, roomId).findFirst();
        if (mRoom != null) {

            if (changeListener == null) {

                changeListener = new RealmChangeListener<RealmModel>() {
                    @Override
                    public void onChange(final RealmModel element) {
                        G.handler.post(new Runnable() {
                            @Override
                            public void run() {
                                if (((RealmRoom) element).isValid()) {
                                    String countText = ((RealmRoom) element).getSharedMediaCount();
                                    if (HelperCalander.isPersianUnicode) {
                                        callbackGroupShearedMedia.set(HelperCalander.convertToUnicodeFarsiNumber(countText));
                                    } else {
                                        callbackGroupShearedMedia.set(countText);
                                    }
                                }
                            }
                        });
                    }
                };
            }

            mRoom.addChangeListener(changeListener);
            changeListener.onChange(mRoom);
        } else {

            callbackGroupShearedMedia.set(context.getString(R.string.there_is_no_sheared_media));
        }
    }
 
Example #9
Source File: FragmentChannelProfileViewModel.java    From iGap-Android with GNU Affero General Public License v3.0 5 votes vote down vote up
public void onResume() {

        mRoom = getRealm().where(RealmRoom.class).equalTo(RealmRoomFields.ID, roomId).findFirst();
        if (mRoom != null) {

            if (changeListener == null) {
                changeListener = new RealmChangeListener<RealmModel>() {
                    @Override
                    public void onChange(final RealmModel element) {
                        G.handler.post(new Runnable() {
                            @Override
                            public void run() {
                                if (((RealmRoom) element).isValid()) {
                                    String countText = ((RealmRoom) element).getSharedMediaCount();
                                    if (HelperCalander.isPersianUnicode) {
                                        callbackChannelSharedMedia.set(HelperCalander.convertToUnicodeFarsiNumber(countText));
                                    } else {
                                        callbackChannelSharedMedia.set(countText);
                                    }
                                }
                            }
                        });
                    }
                };
            }

            mRoom.addChangeListener(changeListener);
            changeListener.onChange(mRoom);
        } else {
            if (callbackChannelSharedMedia.get() != null) {
                callbackChannelSharedMedia.set(context.getString(R.string.there_is_no_sheared_media));
            }
        }
    }
 
Example #10
Source File: FragmentPrivacyAndSecurityViewModel.java    From iGap-Android with GNU Affero General Public License v3.0 5 votes vote down vote up
private void getInfo() {
    realmPrivacy = realm.where(RealmPrivacy.class).findFirst();
    realmUserInfo = realm.where(RealmUserInfo.class).findFirst();
    RealmPrivacy.getUpdatePrivacyFromServer();
    sharedPreferences = G.fragmentActivity.getSharedPreferences(SHP_SETTING.FILE_NAME, MODE_PRIVATE);
    poSelfRemove = sharedPreferences.getInt(SHP_SETTING.KEY_POSITION_SELF_REMOVE, 2);

    updatePrivacyUI(realmPrivacy);

    userInfoListener = new RealmChangeListener<RealmModel>() {
        @Override
        public void onChange(RealmModel element) {

            if (((RealmUserInfo) element).isValid()) {
                selfRemove = ((RealmUserInfo) element).getSelfRemove();
                setTextSelfDestructs();
            }
        }
    };

    privacyListener = new RealmChangeListener<RealmModel>() {
        @Override
        public void onChange(RealmModel element) {
            updatePrivacyUI((RealmPrivacy) element);
        }
    };
}
 
Example #11
Source File: BaseRealmDaoTest.java    From mvvm-template with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void setup() throws Exception {
    super.setup();
    testComponent.inject(this);

    query = initRealmQuery(mockRealm, TestModel.class);
    doNothing().when(mockRealm).beginTransaction();
    doNothing().when(mockRealm).commitTransaction();
    doNothing().when(mockRealm).insertOrUpdate(Matchers.any(RealmModel.class));
    // noinspection unchecked
    doNothing().when(mockRealm).insertOrUpdate(Matchers.any(Collection.class));
}
 
Example #12
Source File: Monarchy.java    From realm-monarchy with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a LiveData that evaluates the new results on a background looper thread.
 *
 * The resulting list is driven by a PositionalDataSource from the Paging Library.
 *
 * The fetch executor of the provided LivePagedListBuilder will be overridden with Monarchy's own FetchExecutor that Monarchy runs its queries on.
 */
public <R, T extends RealmModel> LiveData<PagedList<R>> findAllPagedWithChanges(DataSource.Factory<Integer, T> dataSourceFactory, LivePagedListBuilder<Integer, R> livePagedListBuilder) {
    assertMainThread();
    final MediatorLiveData<PagedList<R>> mediator = new MediatorLiveData<>();
    if(!(dataSourceFactory instanceof RealmDataSourceFactory)) {
        throw new IllegalArgumentException(
                "The DataSource.Factory provided to this method as the first argument must be the one created by Monarchy.");
    }
    RealmDataSourceFactory<T> realmDataSourceFactory = (RealmDataSourceFactory<T>) dataSourceFactory;
    PagedLiveResults<T> liveResults = realmDataSourceFactory.pagedLiveResults;
    mediator.addSource(liveResults, new Observer<PagedList<T>>() {
        @Override
        public void onChanged(@Nullable PagedList<T> ts) {
            // do nothing, this is to intercept `onActive()` calls to ComputableLiveData
        }
    });
    LiveData<PagedList<R>> computableLiveData = livePagedListBuilder
            .setFetchExecutor(new RealmQueryExecutor(this))
            .build();
    mediator.addSource(computableLiveData, new Observer<PagedList<R>>() {
        @Override
        public void onChanged(@Nullable PagedList<R> data) {
            mediator.postValue(data);
        }
    });
    return mediator;
}
 
Example #13
Source File: Monarchy.java    From realm-monarchy with Apache License 2.0 5 votes vote down vote up
/**
 * Provides ability to synchronously fetch a copied RealmResults.
 *
 * @param query Query
 * @param <T>   RealmObject type
 * @return the copied list
 */
public <T extends RealmModel> List<T> fetchAllCopiedSync(final Query<T> query) {
    final AtomicReference<List<T>> ref = new AtomicReference<>();
    doWithRealm(new RealmBlock() {
        @Override
        public void doWithRealm(Realm realm) {
            ref.set(realm.copyFromRealm(query.createQuery(realm).findAll()));
        }
    });
    return Collections.unmodifiableList(ref.get());
}
 
Example #14
Source File: Monarchy.java    From realm-monarchy with Apache License 2.0 5 votes vote down vote up
<T extends RealmModel> void stopListening(@Nullable final LiveResults<T> liveResults) {
    Handler handler = this.handler.get();
    if(handler == null) {
        return; // edge case, hopefully doesn't happen
    }
    // destroy Realm query
    handler.post(new Runnable() {
        @Override
        public void run() {
            destroyRealmQuery(liveResults);
        }
    });
    // destroy Realm instance
    handler.post(new Runnable() {
        @Override
        public void run() {
            synchronized(LOCK) {
                if(refCount.decrementAndGet() == 0) {
                    Realm realm = realmThreadLocal.get();
                    checkRealmValid(realm);
                    realm.close();
                    if(Realm.getLocalInstanceCount(getRealmConfiguration()) <= 0) {
                        realmThreadLocal.set(null);
                    }
                    HandlerThread handlerThread = Monarchy.this.handlerThread.getAndSet(null);
                    Monarchy.this.handler.set(null);
                    handlerThread.quit();
                }
            }
        }
    });
}
 
Example #15
Source File: Monarchy.java    From realm-monarchy with Apache License 2.0 5 votes vote down vote up
<T extends RealmModel> void startListening(@Nullable final LiveResults<T> liveResults) {
    // build Realm instance
    if(refCount.getAndIncrement() == 0) {
        synchronized(LOCK) {
            HandlerThread handlerThread = new HandlerThread("MONARCHY_REALM-#" + hashCode());
            handlerThread.start();
            Handler handler = new Handler(handlerThread.getLooper());
            this.handlerThread.set(handlerThread);
            this.handler.set(handler);
            handler.post(new Runnable() {
                @Override
                public void run() {
                    Realm realm = Realm.getInstance(getRealmConfiguration());
                    if(realmThreadLocal.get() == null) {
                        realmThreadLocal.set(realm);
                    }
                }
            });
        }
    }

    // build Realm query
    handler.get().post(new Runnable() {
        @Override
        public void run() {
            createAndObserveRealmQuery(liveResults);
        }
    });
}
 
Example #16
Source File: Monarchy.java    From realm-monarchy with Apache License 2.0 5 votes vote down vote up
<T extends RealmModel> void destroyRealmQuery(final LiveResults<T> liveResults) {
    Realm realm = realmThreadLocal.get();
    checkRealmValid(realm);
    if(liveResults == null) {
        return;
    }
    RealmResults<? extends RealmModel> realmResults = resultsRefs.get().remove(liveResults);
    if(realmResults != null) {
        realmResults.removeAllChangeListeners();
    }
}
 
Example #17
Source File: Monarchy.java    From realm-monarchy with Apache License 2.0 4 votes vote down vote up
private <T extends RealmModel> LiveData<ManagedChangeSet<T>> findAllManagedWithChanges(Query<T> query, boolean asAsync) {
    assertMainThread();
    return new ManagedLiveResults<>(this, query, asAsync);
}
 
Example #18
Source File: NetworkService.java    From quill with MIT License 4 votes vote down vote up
private <T extends RealmModel> T createOrUpdateModel(T object) {
    return createOrUpdateModel(object, null);
}
 
Example #19
Source File: NetworkService.java    From quill with MIT License 4 votes vote down vote up
private <T extends RealmModel> List<T> createOrUpdateModel(Iterable<T> objects) {
    return createOrUpdateModel(objects, null);
}
 
Example #20
Source File: NetworkService.java    From quill with MIT License 4 votes vote down vote up
private <T extends RealmModel> void deleteModel(T realmObject) {
    RealmUtils.executeTransaction(mRealm, realm -> {
        RealmObject.deleteFromRealm(realmObject);
    });
}
 
Example #21
Source File: Monarchy.java    From realm-monarchy with Apache License 2.0 4 votes vote down vote up
@Override
protected Map<LiveResults<? extends RealmModel>, RealmResults<? extends RealmModel>> initialValue() {
    return new IdentityHashMap<>();
}
 
Example #22
Source File: Monarchy.java    From realm-monarchy with Apache License 2.0 2 votes vote down vote up
/**
 * Returns a LiveData that evaluates the new results on the UI thread, using Realm's Async Query API. The observer receives new data when the database changes.
 *
 * The managed change set contains the OrderedCollectionChangeSet evaluated by Realm.
 *
 * @param query the query
 * @param <T>   the RealmModel type
 * @return the LiveData
 */
public <T extends RealmModel> LiveData<ManagedChangeSet<T>> findAllManagedWithChanges(Query<T> query) {
    return findAllManagedWithChanges(query, true);
}
 
Example #23
Source File: Monarchy.java    From realm-monarchy with Apache License 2.0 2 votes vote down vote up
/**
 * Returns a LiveData that evaluates the new results on the UI thread, using Realm's Sync Query API. The observer receives new data when the database changes.
 *
 * The managed change set contains the OrderedCollectionChangeSet evaluated by Realm.
 *
 * @param query the query
 * @param <T>   the RealmModel type
 * @return the LiveData
 */
public <T extends RealmModel> LiveData<ManagedChangeSet<T>> findAllManagedWithChangesSync(Query<T> query) {
    return findAllManagedWithChanges(query, false);
}
 
Example #24
Source File: Monarchy.java    From realm-monarchy with Apache License 2.0 2 votes vote down vote up
/**
 * Creates a DataSource.Factory of (Integer, T) that can be used for creating a paged result set.
 *
 * By default behavior, the created query is synchronous.
 *
 * @param query the query
 */
public <T extends RealmModel> RealmDataSourceFactory<T> createDataSourceFactory(Query<T> query) {
    assertMainThread();
    PagedLiveResults<T> liveResults = new PagedLiveResults<T>(this, query, false);
    return new RealmDataSourceFactory<>(this, liveResults);
}
 
Example #25
Source File: Monarchy.java    From realm-monarchy with Apache License 2.0 2 votes vote down vote up
/**
 * Returns a LiveData that evaluates the new results on a background looper thread. The observer receives new data when the database changes.
 *
 * The items are mapped out with the provided {@link Mapper}.
 *
 * @param query the query
 * @param <T>   the RealmModel type
 * @param <U>   the mapped type
 * @return the LiveData
 */
public <T extends RealmModel, U> LiveData<List<U>> findAllMappedWithChanges(Query<T> query, Mapper<U, T> mapper) {
    assertMainThread();
    return new MappedLiveResults<>(this, query, mapper);
}
 
Example #26
Source File: Monarchy.java    From realm-monarchy with Apache License 2.0 2 votes vote down vote up
/**
 * Returns a LiveData that evaluates the new results on a background looper thread. The observer receives new data when the database changes.
 *
 * The items are frozen with `realmResults.freeze()`.
 *
 * @param query the query
 * @param <T>   the RealmModel type
 * @return the LiveData
 */
public <T extends RealmModel> LiveData<List<T>> findAllFrozenWithChanges(Query<T> query) {
    assertMainThread();
    return new FrozenLiveResults<>(this, query);
}
 
Example #27
Source File: Monarchy.java    From realm-monarchy with Apache License 2.0 2 votes vote down vote up
/**
 * Returns a LiveData that evaluates the new results on a background looper thread. The observer receives new data when the database changes.
 *
 * The items are copied out with `realm.copyFromRealm(results)`.
 *
 * @param query the query
 * @param <T>   the RealmModel type
 * @return the LiveData
 */
public <T extends RealmModel> LiveData<List<T>> findAllCopiedWithChanges(Query<T> query) {
    assertMainThread();
    return new CopiedLiveResults<>(this, query);
}
 
Example #28
Source File: Monarchy.java    From realm-monarchy with Apache License 2.0 2 votes vote down vote up
/**
 * Provides ability to synchronously obtain a managed RealmResults as a List, in a safe way.
 *
 * What is actually returned is a snapshot collection.
 *
 * This method only makes sense either if Realm is opened manually, or inside a {@link Monarchy#doWithRealm(RealmBlock)} (or {@link Monarchy#runTransactionSync(Realm.Transaction)} method).
 *
 * @param realm Realm
 * @param query Query
 * @param <T>   RealmObject type
 * @return the snapshot collection
 */
public <T extends RealmModel> List<T> fetchAllManagedSync(Realm realm, Query<T> query) {
    return query.createQuery(realm).findAll().createSnapshot();
}