@Override public void subscribeDataChange(Object dataIdentity, final DataChangeListener listener) { if (dataIdentity instanceof RealmResults) { RealmResults<RealmObject> realmResults = (RealmResults<RealmObject>) dataIdentity; realmResults.addChangeListener(new RealmChangeListener<RealmResults<RealmObject>>() { @Override public void onChange(RealmResults<RealmObject> element) { if (listener != null) { listener.onChange(); } } }); } }
/** * Make gson which {@link DateDeserializer} and compatible with {@link RealmObject} * @return {@link Gson} object */ public static Gson makeGsonForRealm() { return makeDefaultGsonBuilder() .setExclusionStrategies(new ExclusionStrategy() { @Override public boolean shouldSkipField(FieldAttributes f) { return f.getDeclaringClass().equals(RealmObject.class); } @Override public boolean shouldSkipClass(Class<?> clazz) { return false; } }) .create(); }
public <E extends RealmObject> void deleteAllIn(Class<E> classType, String classField, String[] fieldsIn) { Realm realm = get(); try { realm.beginTransaction(); realm.where(classType) .in(classField, fieldsIn) .findAll() .deleteAllFromRealm(); realm.commitTransaction(); } finally { if (realm != null) { realm.close(); } } }
@Override public void onClick(View v) { Context c = RealmBrowserSampleActivity.this; RealmConfiguration firstConfig = new RealmConfiguration.Builder().build(); Realm realm = Realm.getInstance(firstConfig); RealmConfiguration secondRealmConfig = new RealmConfiguration.Builder() .name(SECOND_REALM_NAME) .build(); Realm realmSecond = Realm.getInstance(secondRealmConfig); List<Class<? extends RealmObject>> classes = new ArrayList<>(); classes.add(Cat.class); classes.add(Dog.class); classes.add(Person.class); classes.add(DataTypeTest.class); new RealmBrowser.Builder(c) .add(realm, classes) .add(realmSecond, DifferentFileObject.class) .show(); }
@Override public <Item extends RealmObject> Observable<List<Item>> getApiObservable(Observable<List<Item>> api, Class<Item> realmClass, String sortedField, List<Integer> ids) { if (getStorage() != null) { RealmResults<Item> realmResults; if (sortedField != null) realmResults = (ids == null) ? getItems(realmClass, sortedField) : getItems(realmClass, sortedField, ids); else realmResults = getItems(realmClass); Observable<List<Item>> realmObserver = realmResults.asObservable() .filter(RealmResults::isLoaded) .compose(getLifecycle()) .switchMap(Observable::just); Observable<List<Item>> retrofitObserver = api .compose(applySchedulers()) .compose(getLifecycle()); return Observable.<List<Item>>create(subscriber -> { realmObserver.take(2).subscribe(subscriber::onNext, subscriber::onError, subscriber::onCompleted); retrofitObserver.subscribe(this::setItems, subscriber::onError); }).compose(getLifecycle()); } else return api; }
/** * Puts and element into the DB. * * @param jsonObject Element to insert in the DB. * @param dataClass Class type of the items to be put. */ @NonNull @Override public Single<Boolean> put(@Nullable JSONObject jsonObject, @Nullable String idColumnName, Class itemIdType, @NonNull Class dataClass) { return Single.fromCallable(() -> { if (jsonObject == null) { throw new IllegalArgumentException("JSONObject is invalid"); } else { updateJsonObjectWithIdValue(jsonObject, idColumnName, itemIdType, dataClass); return getRealm(Realm.getDefaultInstance()).map(realm1 -> RealmObject.isValid(executeWriteOperationInRealm(realm1, () -> realm1.createOrUpdateObjectFromJson(dataClass, jsonObject)))) .blockingFirst(); } }); }
@Override public void onClick(View v) { Context c = MainActivity.this; RealmConfiguration firstConfig = new RealmConfiguration.Builder().build(); RealmConfiguration secondRealmConfig = new RealmConfiguration.Builder() .name(SECOND_REALM_NAME) .schemaVersion(5) .migration(mMigration) .build(); List<Class<? extends RealmObject>> classes = new ArrayList<>(); classes.add(Cat.class); classes.add(Dog.class); classes.add(Person.class); classes.add(DataTypeTest.class); new RealmBrowser.Builder(c) .add(firstConfig, classes) .add(secondRealmConfig, DifferentFileObject.class) .show(); }
@Override public RealmObject convert(Cursor cursor, PackageManager packageManager, Context context) { cm.aptoide.pt.database.realm.Update realmObject = new cm.aptoide.pt.database.realm.Update(); realmObject.setPackageName(cursor.getString(cursor.getColumnIndex(COLUMN_PACKAGE_NAME))); realmObject.setLabel(cursor.getString(cursor.getColumnIndex(COLUMN_NAME))); realmObject.setVersionCode(cursor.getInt(cursor.getColumnIndex(COLUMN_VERCODE))); realmObject.setUpdateVersionName(cursor.getString(cursor.getColumnIndex(COLUMN_VERNAME))); realmObject.setExcluded(true); String cleanIconPath = AptoideUtils.IconSizeU.cleanImageUrl( cursor.getString(cursor.getColumnIndex(COLUMN_ICONPATH))); realmObject.setIcon(cleanIconPath); // are this columns to remove? // COLUMN_NAME return realmObject; }
public <E extends RealmObject> void deleteAllExcluding(Class<E> classType, String classField, List<String> fieldsIn) { Realm realm = get(); try { realm.beginTransaction(); RealmQuery<E> query = realm.where(classType); for (String field : fieldsIn) { query.notEqualTo(classField, field); } query.findAll() .deleteAllFromRealm(); realm.commitTransaction(); } finally { if (realm != null) { realm.close(); } } }
/** * Custom Gson to make Retrofit Gson adapter work with Realm objects */ @NonNull @Provides @Singleton public static Gson provideGson(@NonNull ListTypeAdapterFactory jsonArrayTypeAdapterFactory, @NonNull HtmlAdapter htmlAdapter, @NonNull StringCapitalizerAdapter stringCapitalizerAdapter) { return new GsonBuilder() .setExclusionStrategies(new ExclusionStrategy() { @Override public boolean shouldSkipField(FieldAttributes f) { return f.getDeclaringClass().equals(RealmObject.class); } @Override public boolean shouldSkipClass(Class<?> clazz) { return false; } }) .registerTypeAdapterFactory(jsonArrayTypeAdapterFactory) .registerTypeAdapter(String.class, htmlAdapter) .registerTypeAdapter(String.class, stringCapitalizerAdapter) .create(); }
static String getFieldDisplayedName(@NonNull RealmObject obj, @NonNull Field field) { if (isFieldRealmList(field)) { return getRealmListFieldDisplayingName(obj, field); } else if (isFieldRealmObject(field)) { Object value = getRealmObjectFieldValue(obj, field); return value == null ? "null" : getRealmObjectFieldDisplayingName(field); } else { Object result = getNotParamFieldValue(obj, field); if (result != null) { if (field.getType() == byte[].class || field.getType() == Byte[].class) { byte[] array = (byte[]) result; StringBuilder builder = new StringBuilder(); for (byte b : array) { builder.append(String.format("0x%02X", b)); builder.append(" "); } return builder.toString(); } } return result == null ? "null" : result.toString(); } }
private static String getRealmListFieldDisplayingName(@NonNull RealmObject obj, @NonNull Field field) { ParameterizedType pType = (ParameterizedType) field.getGenericType(); String rawType = pType.getRawType().toString(); int rawTypeIndex = rawType.lastIndexOf("."); if (rawTypeIndex > 0) { rawType = rawType.substring(rawTypeIndex + 1); } String argument = pType.getActualTypeArguments()[0].toString(); int argumentIndex = argument.lastIndexOf("."); if (argumentIndex > 0) { argument = argument.substring(argumentIndex + 1); } int objNumber = RealmUtils.getRealmListFieldValue(obj, field).size(); return String.format("%s<%s> (%d)", rawType, argument, objNumber); }
List<Class<? extends RealmObject>> getDisplayedRealmObjects(RealmConfiguration realm) { List<Class<? extends RealmObject>> result = new ArrayList<>(); for (Class<? extends RealmObject> clazz : displayedRealmConfigs.keySet()) { RealmConfiguration config = displayedRealmConfigs.get(clazz); if (config.getPath().equals(realm.getPath())) { result.add(clazz); } } Collections.sort(result, new Comparator<Class<? extends RealmObject>>() { @Override public int compare(Class<? extends RealmObject> lhs, Class<? extends RealmObject> rhs) { return lhs.getSimpleName().compareTo(rhs.getSimpleName()); } }); return result; }
private void fillTable(RealmObject realmObj, Field field) { if (RealmUtils.isFieldRealmList(field)) { ParameterizedType pType = (ParameterizedType) field.getGenericType(); //noinspection unchecked mClazz = (Class<? extends RealmObject>) pType.getActualTypeArguments()[0]; mOriginalData = RealmUtils.getRealmListFieldValue(realmObj, field); } else if (RealmUtils.isFieldRealmObject(field)) { //noinspection unchecked mClazz = (Class<? extends RealmObject>) field.getType(); mOriginalData = new ArrayList<>(1); mOriginalData.add(RealmUtils.getRealmObjectFieldValue(realmObj, field)); } else { throw new IllegalArgumentException("Unsupported field type: " + field); } updateData(mOriginalData); }
public static Gson getGsonInstance(){ return new GsonBuilder() .setExclusionStrategies(new ExclusionStrategy() { @Override public boolean shouldSkipField(FieldAttributes f) { return f.getDeclaringClass().equals(RealmObject.class); } @Override public boolean shouldSkipClass(Class<?> clazz) { return false; } }) .setDateFormat("yyyy-MM-dd'T'HH:mm:ss") .create(); }
/** * Normalizes a input class to it's original RealmObject class so it is transparent whether or not the input class * was a RealmProxy class. */ public static Class<? extends RealmModel> getOriginalModelClass(Class<? extends RealmModel> clazz) { // This cast is correct because 'clazz' is either the type // generated by RealmProxy or the original type extending directly from RealmObject. @SuppressWarnings("unchecked") Class<? extends RealmModel> superclass = (Class<? extends RealmModel>) clazz.getSuperclass(); if (!superclass.equals(Object.class) && !superclass.equals(RealmObject.class)) { clazz = superclass; } return clazz; }
@Override public <E extends RealmModel> Flowable<E> from(final Realm realm, final E object) { final RealmConfiguration realmConfig = realm.getConfiguration(); return Flowable.create(new FlowableOnSubscribe<E>() { @Override public void subscribe(final FlowableEmitter<E> emitter) throws Exception { // Gets instance to make sure that the Realm is open for as long as the // Observable is subscribed to it. final Realm observableRealm = Realm.getInstance(realmConfig); objectRefs.get().acquireReference(object); final RealmChangeListener<E> listener = new RealmChangeListener<E>() { @Override public void onChange(E obj) { if (!emitter.isCancelled()) { emitter.onNext(obj); } } }; RealmObject.addChangeListener(object, listener); // Cleanup when stream is disposed emitter.setDisposable(Disposables.fromRunnable(new Runnable() { @Override public void run() { RealmObject.removeChangeListener(object, listener); observableRealm.close(); objectRefs.get().releaseReference(object); } })); // Emit current value immediately emitter.onNext(object); } }, BACK_PRESSURE_STRATEGY); }
@Override public <E extends RealmModel> Observable<ObjectChange<E>> changesetsFrom(Realm realm, final E object) { final RealmConfiguration realmConfig = realm.getConfiguration(); return Observable.create(new ObservableOnSubscribe<ObjectChange<E>>() { @Override public void subscribe(final ObservableEmitter<ObjectChange<E>> emitter) throws Exception { // Gets instance to make sure that the Realm is open for as long as the // Observable is subscribed to it. final Realm observableRealm = Realm.getInstance(realmConfig); objectRefs.get().acquireReference(object); final RealmObjectChangeListener<E> listener = new RealmObjectChangeListener<E>() { @Override public void onChange(E obj, ObjectChangeSet changeSet) { if (!emitter.isDisposed()) { emitter.onNext(new ObjectChange<>(obj, changeSet)); } } }; RealmObject.addChangeListener(object, listener); // Cleanup when stream is disposed emitter.setDisposable(Disposables.fromRunnable(new Runnable() { @Override public void run() { RealmObject.removeChangeListener(object, listener); observableRealm.close(); objectRefs.get().releaseReference(object); } })); // Emit current value immediately emitter.onNext(new ObjectChange<>(object, null)); } }); }
@Override public Flowable<DynamicRealmObject> from(DynamicRealm realm, final DynamicRealmObject object) { final RealmConfiguration realmConfig = realm.getConfiguration(); return Flowable.create(new FlowableOnSubscribe<DynamicRealmObject>() { @Override public void subscribe(final FlowableEmitter<DynamicRealmObject> emitter) throws Exception { // Gets instance to make sure that the Realm is open for as long as the // Observable is subscribed to it. final DynamicRealm observableRealm = DynamicRealm.getInstance(realmConfig); objectRefs.get().acquireReference(object); final RealmChangeListener<DynamicRealmObject> listener = new RealmChangeListener<DynamicRealmObject>() { @Override public void onChange(DynamicRealmObject obj) { if (!emitter.isCancelled()) { emitter.onNext(obj); } } }; RealmObject.addChangeListener(object, listener); // Cleanup when stream is disposed emitter.setDisposable(Disposables.fromRunnable(new Runnable() { @Override public void run() { RealmObject.removeChangeListener(object, listener); observableRealm.close(); objectRefs.get().releaseReference(object); } })); // Emit current value immediately emitter.onNext(object); } }, BACK_PRESSURE_STRATEGY); }
/** * Deletes an row from Realm for the model class and primary key given if it exists. * @return true if the object existed, false if not. */ public <T extends RealmModel> boolean deleteIfExists(Class<T> clazz, String primaryKey) { T model = RealmQueries.withRealm(realm).get(clazz, primaryKey); if (model == null) { return false; } RealmObject.deleteFromRealm(model); return false; }
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(); } }); }
public <T extends RealmObject> void deleteTopicMessage(Class<T> clazz, String topic) { final RealmResults results = mRealm.where(clazz) .equalTo("topic", topic) .findAll(); mRealm.executeTransaction(new Realm.Transaction() { @Override public void execute(Realm realm) { results.deleteAllFromRealm(); } }); }
public <T extends RealmObject> void deleteTopic(Class<T> clazz, String id) { final RealmResults results = mRealm.where(clazz) .equalTo("connectionId", id) .findAll(); mRealm.executeTransaction(new Realm.Transaction() { @Override public void execute(Realm realm) { results.deleteAllFromRealm(); } }); }
@Override public void unsubscribeDataChange(Object dataIdentity) { if (dataIdentity instanceof RealmResults) { RealmResults<RealmObject> realmResults = (RealmResults<RealmObject>) dataIdentity; realmResults.removeChangeListeners(); } }
public <O extends RealmObject> RealmQuery<O> copyToRealmQuery(RealmQuery<O> query){ Iterator it = filters.entrySet().iterator(); while (it.hasNext()) { Map.Entry pair = (Map.Entry)it.next(); if(pair.getValue() instanceof Byte){ query.equalTo((String) pair.getKey(), (Byte) pair.getValue()); } else if(pair.getValue() instanceof Boolean){ query.equalTo((String) pair.getKey(), (Boolean) pair.getValue()); } else if(pair.getValue() instanceof Date){ query.equalTo((String) pair.getKey(), (Date) pair.getValue()); } else if(pair.getValue() instanceof byte[]){ query.equalTo((String) pair.getKey(), (byte[]) pair.getValue()); } else if(pair.getValue() instanceof Integer){ query.equalTo((String) pair.getKey(), (Integer) pair.getValue()); } else if(pair.getValue() instanceof Short){ query.equalTo((String) pair.getKey(), (Short) pair.getValue()); } else if(pair.getValue() instanceof Long){ query.equalTo((String) pair.getKey(), (Long) pair.getValue()); } else if(pair.getValue() instanceof Float){ query.equalTo((String) pair.getKey(), (Float) pair.getValue()); } else if(pair.getValue() instanceof Double){ query.equalTo((String) pair.getKey(), (Double) pair.getValue()); } else if(pair.getValue() instanceof String){ query.equalTo((String) pair.getKey(), (String) pair.getValue()); } it.remove(); } return query; }
public static <O extends RealmObject> void saveOrUpdate(Realm realmInstance, O object) { Realm realm = realmInstance; realm.beginTransaction(); realm.copyToRealmOrUpdate(object); realm.commitTransaction(); realm.close(); }
public static <O extends RealmObject> void saveOrUpdate(Realm realmInstance,O object, OnTransactionCallback callback) { Realm realm = realmInstance; realm.executeTransactionAsync( realm1 -> realm1.copyToRealmOrUpdate(object), callback::onSuccess, callback::onError ); }
public static <O extends RealmObject> O get(Realm realmInstance, QueryFilters filters, Class<O> clazz) throws LocalDataNotFoundException{ Realm realm = realmInstance; RealmQuery<O> query = realm.where(clazz); query = filters.copyToRealmQuery(query); O result = query.findFirst(); if(result != null){ O finalResult = realm.copyFromRealm(result); realm.close(); return finalResult; } throw new SessionNotFoundException("queried data is not found"); }
public static <O extends RealmObject> void delete(Realm realmInstance, QueryFilters filters, Class<O> clazz){ Realm realm = realmInstance; realm.beginTransaction(); RealmQuery<O> query = realm.where(clazz); query = filters.copyToRealmQuery(query); final RealmResults<O> results = query.findAll(); results.deleteAllFromRealm(); realm.commitTransaction(); realm.close(); }
public static <O extends RealmObject> List<O> getList(Realm realmInstance, QueryFilters filters, Class<O> clazz) throws LocalDataNotFoundException{ Realm realm = realmInstance; RealmQuery<O> query = realm.where(clazz); query = filters.copyToRealmQuery(query); List<O> results = realm.copyFromRealm(query.findAll()); realm.close(); return results; }
@Override public RealmObject delete(String cacheId, Class<? extends RealmObject> aClass) { Realm realm = Realm.getDefaultInstance(); realm.beginTransaction(); RealmObject realmObject = realm.where(aClass).endsWith("cacheId", cacheId).findFirst(); realmObject.deleteFromRealm(); realm.commitTransaction(); return null; }
@Override public void toParcel(RealmList<? extends RealmObject> input, Parcel parcel) { parcel.writeInt(input == null ? NULL : input.size()); if (input != null) { for (RealmObject item : input) { parcel.writeParcelable(Parcels.wrap(item), 0); } } }
@Override public RealmList fromParcel(Parcel parcel) { int size = parcel.readInt(); if (size != -1) { RealmList list = new RealmList(); for (int i = 0; i < size; i++) { Parcelable parcelable = parcel.readParcelable(getClass().getClassLoader()); list.add((RealmObject) Parcels.unwrap(parcelable)); } return list; } return null; }
private void clearAndSetPendingActionOnPost(@NonNull Post post, @PendingAction.Type String newPendingAction) { List<PendingAction> pendingActions = post.getPendingActions(); mRealm.executeTransaction(realm -> { // make a copy since the original is a live-updating RealmList List<PendingAction> pendingActionsCopy = new ArrayList<>(pendingActions); for (PendingAction pa : pendingActionsCopy) { RealmObject.deleteFromRealm(pa); } pendingActions.clear(); post.addPendingAction(newPendingAction); }); }
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); } }); }
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(""); } } }
public static <T extends RealmObject> Flowable<T> listenElement( final Function<Realm, RealmResults<T>> query) { final AtomicReference<Realm> realmReference = new AtomicReference<>(null); return listenRealmResults(query, realmReference) .filter(result -> !result.isEmpty()) .map(result -> realmReference.get().copyFromRealm(result.first())); }
public static <T extends RealmObject> Maybe<List<T>> getList( final Function<Realm, RealmResults<T>> query) { return Maybe.create(emitter -> { final Realm realm = Realm.getDefaultInstance(); final RealmResults<T> result = query.apply(realm); if (result != null && result.isLoaded() && result.isValid()) { emitter.onSuccess(realm.copyFromRealm(result)); } else { emitter.onComplete(); } emitter.setCancellable(realm::close); }); }
public static <T extends RealmObject> Maybe<T> getElement(final Function<Realm, T> query) { return Maybe.create(emitter -> { final Realm realm = Realm.getDefaultInstance(); final T result = query.apply(realm); if (result != null && result.isLoaded() && result.isValid()) { emitter.onSuccess(realm.copyFromRealm(result)); } else { emitter.onComplete(); } emitter.setCancellable(realm::close); }); }
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); }); }