io.realm.RealmQuery Java Examples

The following examples show how to use io.realm.RealmQuery. 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: AddContactDialogFragment.java    From natrium-android-wallet with BSD 2-Clause "Simplified" License 6 votes vote down vote up
private boolean validateAddress() {
    // check for valid address
    if (binding.contactAddress.getText().toString().trim().isEmpty()) {
        showAddressError(R.string.send_enter_address);
        return false;
    }
    Address address = new Address(binding.contactAddress.getText().toString());
    if (!address.isValidAddress()) {
        showAddressError(R.string.send_invalid_address);
        return false;
    }
    RealmQuery realmQuery = realm.where(Contact.class);
    realmQuery.equalTo("address", address.getAddress());
    if (realmQuery.count() > 0) {
        showAddressError(R.string.contact_address_exists);
        return false;
    }
    hideAddressError();
    return true;
}
 
Example #2
Source File: AddContactDialogFragment.java    From natrium-android-wallet with BSD 2-Clause "Simplified" License 6 votes vote down vote up
private boolean validateName() {
    String name = binding.contactName.getText().toString().trim();
    if (!name.startsWith("@")) {
        name = "@" + name;
    }
    if (name.isEmpty() || name.length() <= 1) {
        showNameError(R.string.contact_name_missing);
        return false;
    } else {
        RealmQuery realmQuery = realm.where(Contact.class);
        realmQuery.equalTo("name", name);
        if (realmQuery.count() > 0) {
            showNameError(R.string.contact_name_exists);
            return false;
        }
    }
    hideNameError();
    return true;
}
 
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: Database.java    From udacity-p1-p2-popular-movies with MIT License 6 votes vote down vote up
private <T extends RealmObject> void readAllAsync(@NonNull final ReadAction<T> readAction) {
    Realm realm = null;
    try {
        realm = Realm.getDefaultInstance();
        RealmQuery<T> query = readAction.getQuery(realm);
        final RealmResults<T> results = query.findAllAsync();
        results.addChangeListener(new RealmChangeListener() {
            @Override
            public void onChange() {
                results.removeChangeListener(this);
                readAction.onResults(results);
            }
        });
    } finally {
        if (realm != null) {
            realm.close();
        }
    }
}
 
Example #5
Source File: Database.java    From udacity-p1-p2-popular-movies with MIT License 6 votes vote down vote up
public void loadMovie(final int id, final ReadCallback<Movie> callback) {
    if (BuildConfig.DEBUG) {
        Log.d(TAG, "[READ ] Load Movie with id = " + id);
    }
    readAllAsync(new ReadAction<Movie>() {
        @NonNull
        @Override
        public RealmQuery<Movie> getQuery(@NonNull Realm realm) {
            return realm.where(Movie.class).equalTo("id", id);
        }

        @Override
        public void onResults(RealmResults<Movie> results) {
            if (!results.isEmpty()) {
                if (BuildConfig.DEBUG) {
                    Log.d(TAG, "[READ ] Success: Movie with id = " + id);
                }
                callback.done(AppUtil.copy(results.first(), Movie.class));
            } else {
                callback.failed(new RuntimeException("No Movie found with id = " + id));
            }
        }
    });
}
 
Example #6
Source File: Database.java    From udacity-p1-p2-popular-movies with MIT License 6 votes vote down vote up
public void loadFavoriteMovies(final ReadCallback<List<Movie>> callback) {
    readAllAsync(new ReadAction<Movie>() {
        @NonNull
        @Override
        public RealmQuery<Movie> getQuery(@NonNull Realm realm) {
            return realm.where(Movie.class).equalTo("isFavorite", true);
        }

        @Override
        public void onResults(RealmResults<Movie> results) {
            List<Movie> favorites = new ArrayList<>(results.size());
            for (Movie movie : results) {
                favorites.add(AppUtil.copy(movie, Movie.class));
            }
            callback.done(favorites);
        }
    });
}
 
Example #7
Source File: Database.java    From aptoide-client-v8 with GNU General Public License v3.0 6 votes vote down vote up
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();
    }
  }
}
 
Example #8
Source File: ReadDataActivity.java    From example with Apache License 2.0 5 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_read_data);

    realm = Realm.getInstance(this);

    RealmQuery<User> query = realm.where(User.class);
    RealmResults<User> result = query.findAll();

    for (User data : result) {
        Log.d("test", "Name : " + data.getName() + ", age : " + data.getAge());
    }
}
 
Example #9
Source File: HomeFragment.java    From natrium-android-wallet with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private String getContactName(String address) {
    if (mContactCache.containsKey(address)) {
        return mContactCache.get(address);
    }
    RealmQuery realmQuery = realm.where(Contact.class);
    realmQuery.equalTo("address", address);
    if (realmQuery.count() > 0) {
        Contact c = (Contact) realmQuery.findFirst();
        mContactCache.put(address, c.getDisplayName());
        return c.getDisplayName();
    }
    return null;
}
 
Example #10
Source File: Expense.java    From Expense-Tracker-App with MIT License 5 votes vote down vote up
public static RealmResults<Expense> getExpensesList(Date dateFrom, Date dateTo, @IExpensesType Integer type, Category category) {
    RealmQuery<Expense> realmQuery = RealmManager.getInstance().getRealmInstance()
            .where(Expense.class);
    if (dateTo != null) {
        realmQuery.between("date", dateFrom, dateTo);
    } else {
        realmQuery.equalTo("date", dateFrom);
    }
    if (category != null) realmQuery.equalTo("category.id", category.getId());
    if (type != null) realmQuery.equalTo("type", type);
    return realmQuery.findAll();
}
 
Example #11
Source File: RealmBufferResolver.java    From TimberLorry with Apache License 2.0 5 votes vote down vote up
@Override
public void remove(Record record) {
    Realm realm = null;
    try {
        realm = Realm.getInstance(realmConfig);
        realm.beginTransaction();
        RealmQuery<RecordObject> query = realm.where(RecordObject.class);
        query.equalTo("className", record.getClazz().getCanonicalName())
                .equalTo("body", record.getBody()).findAll().remove(0);
        realm.commitTransaction();
    } finally {
        if (realm != null)
            realm.close();
    }
}
 
Example #12
Source File: ApiStorage.java    From ApiClient with Apache License 2.0 5 votes vote down vote up
@Override
public <Item extends RealmObject> RealmResults<Item> getItems(Class<Item> objectClass, String sortedFieldName, List<Integer> ids) {
    RealmQuery<Item> query = getQuery(objectClass);
    for (int i = 0; i < ids.size() - 1; i++) {
        query = query.equalTo(sortedFieldName, ids.get(i)).or();
    }
    query = query.equalTo(sortedFieldName, ids.get(ids.size() - 1));

    return query.findAllSortedAsync(sortedFieldName);
}
 
Example #13
Source File: Database.java    From aptoide-client-v8 with GNU General Public License v3.0 5 votes vote down vote up
public <E extends RealmObject> Observable<List<E>> findAsList(RealmQuery<E> query) {
  return Observable.just(query.findAll())
      .filter(realmObject -> realmObject != null)
      .flatMap(realmObject -> realmObject.<E>asObservable().unsubscribeOn(
          RealmSchedulers.getScheduler()))
      .flatMap(realmObject -> copyFromRealm(realmObject))
      .defaultIfEmpty(null);
}
 
Example #14
Source File: Database.java    From aptoide-client-v8 with GNU General Public License v3.0 5 votes vote down vote up
public <E extends RealmObject> Observable<E> findFirst(RealmQuery<E> query) {
  return Observable.just(query.findFirst())
      .filter(realmObject -> realmObject != null)
      .flatMap(realmObject -> realmObject.<E>asObservable().unsubscribeOn(
          RealmSchedulers.getScheduler()))
      .flatMap(realmObject -> copyFromRealm(realmObject))
      .defaultIfEmpty(null);
}
 
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: DatabaseCurrencyDataSource.java    From exchange-rates-mvvm with Apache License 2.0 5 votes vote down vote up
@Override
public boolean containsCurrencyValue(final Date date, final String currencyCode) {
    final long midnight = midnight(date.getTime());
    return readFromRealmSync((realm) -> {
        final RealmQuery<ValueEntity> query = realm.where(ValueEntity.class)
                .equalTo(ValueEntity.TIMESTAMP, midnight);
        if (!TextUtils.isEmpty(currencyCode)) {
            query.equalTo(ValueEntity.CODE, currencyCode);
        }
        final long etriesCount = query.count();
        return etriesCount != 0;
    });
}
 
Example #17
Source File: RealmMember.java    From iGap-Android with GNU Affero General Public License v3.0 5 votes vote down vote up
public static RealmResults<RealmMember> filterMember(long roomId, @Nullable String filter) {
    Realm realm = Realm.getDefaultInstance();
    RealmRoom realmRoom = realm.where(RealmRoom.class).equalTo(RealmRoomFields.ID, roomId).findFirst();
    if (realmRoom == null) {
        return emptyResult(realm);
    }

    RealmResults<RealmMember> searchMember = emptyResult(realm);
    RealmResults<RealmRegisteredInfo> findMember;

    if (filter != null && filter.length() > 0) {
        findMember = realm.where(RealmRegisteredInfo.class).contains(RealmRegisteredInfoFields.DISPLAY_NAME, filter, Case.INSENSITIVE).findAll().sort(RealmRegisteredInfoFields.DISPLAY_NAME);
    } else {
        findMember = realm.where(RealmRegisteredInfo.class).equalTo(RealmRoomFields.ID, roomId).findAll().sort(RealmRegisteredInfoFields.DISPLAY_NAME);
    }
    try {
        RealmQuery<RealmMember> query;
        if (realmRoom.getType() == GROUP) {
            query = realmRoom.getGroupRoom().getMembers().where();
        } else {
            query = realmRoom.getChannelRoom().getMembers().where();
        }

        for (int i = 0; i < findMember.size(); i++) {
            if (i != 0) {
                query = query.or();
            }
            query = query.equalTo(RealmMemberFields.PEER_ID, findMember.get(i).getId());
        }
        if (findMember.size() > 0 || (filter == null || filter.length() == 0)) {
            searchMember = query.findAll();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return searchMember;
}
 
Example #18
Source File: ManagedLiveResults.java    From realm-monarchy with Apache License 2.0 5 votes vote down vote up
@Override
protected void onActive() {
    realm = Realm.getInstance(realmConfiguration);
    RealmQuery<T> realmQuery = query.createQuery(realm);
    if(asAsync) {
        realmResults = realmQuery.findAllAsync(); // sort/distinct should be done with new queries, 5.0+
    } else {
        realmResults = realmQuery.findAll(); // sort/distinct should be done with new queries, 5.0+
    }
    realmResults.addChangeListener(realmChangeListener);

    if(!asAsync) {
        setValue(new Monarchy.ManagedChangeSet<T>(realmResults, new EmptyChangeSet()));
    }
}
 
Example #19
Source File: PagedFragment.java    From realm-monarchy with Apache License 2.0 5 votes vote down vote up
@OnTextChanged(R.id.text_paged_search)
public void onSearchTextChanged(Editable editable) {
    String text = editable.toString();
    realmDataSourceFactory.updateQuery(realm -> {
        RealmQuery<RealmDog> query = realm.where(RealmDog.class);
        if(text.isEmpty()) {
            return query;
        } else {
            return query.contains(RealmDogFields.NAME, text.trim(), Case.INSENSITIVE);
        }
    });
}
 
Example #20
Source File: NotesFragment.java    From multi-copy with Apache License 2.0 5 votes vote down vote up
private void refreshData(){
    Realm realm = Realm.getDefaultInstance();
    RealmQuery<NotesModel> notesModelRealmQuery = realm.where(NotesModel.class);
    RealmResults<NotesModel> query = notesModelRealmQuery.findAll();
    notesList.clear();
    notesList.addAll(query);
    notesAdapter.notifyDataSetChanged();
}
 
Example #21
Source File: AlarmDAO.java    From sleep-cycle-alarm with GNU General Public License v3.0 4 votes vote down vote up
public List<Alarm> getListOfAlarms() {
    Realm realm = RealmManager.getRealm();
    RealmQuery<Alarm> query = realm.where(Alarm.class);
    return query.findAll();
}
 
Example #22
Source File: DatabaseRealm.java    From openwebnet-android with MIT License 4 votes vote down vote up
private <T extends RealmObject> RealmQuery<T> query(Class<T> clazz) {
    return getRealmInstance().where(clazz);
}
 
Example #23
Source File: EventDao.java    From mvvm-template with GNU General Public License v3.0 4 votes vote down vote up
private RealmQuery<Event> getUserReceivedEventQuery(String userLoginName) {
    return query().equalTo("receivedOwner", userLoginName);
}
 
Example #24
Source File: EventDao.java    From mvvm-template with GNU General Public License v3.0 4 votes vote down vote up
private RealmQuery<Event> getEventsByActorQuery(String actorLoginName) {
    return query().equalTo("actor.login", actorLoginName);
}
 
Example #25
Source File: ApiStorage.java    From ApiClient with Apache License 2.0 4 votes vote down vote up
@Override
public <Item extends RealmObject> RealmQuery<Item> getQuery(Class<Item> objectClass) {
    return mRealm.where(objectClass);
}
 
Example #26
Source File: RealmTestUtils.java    From mvvm-template with GNU General Public License v3.0 4 votes vote down vote up
/**
 * see {@link #initFindAllSorted(RealmQuery, List)}
 */
public static <T extends RealmObject> RealmResults<T> initFindAllSorted(RealmQuery<T> query) throws Exception {
    return initFindAllSorted(query, null);
}
 
Example #27
Source File: RealmTestUtils.java    From mvvm-template with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Must be run with {@link org.powermock.modules.junit4.PowerMockRunner} or {@link org.robolectric.RobolectricTestRunner}
 * Test classes should be annotated {@link org.powermock.core.classloader.annotations.PrepareForTest}
 * : RealmResults.class
 *
 * Initialize findAll and findAllSorted for given {@link RealmQuery}
 *
 * Must be run with {@link org.powermock.modules.junit4.PowerMockRunner} or {@link org.robolectric.RobolectricTestRunner}
 * Test classes should be annotate {@link org.powermock.core.classloader.annotations.PrepareForTest}
 * RealmResults.class, RealmQuery.class
 *
 * @param query mocked query, should be mocked by {@link PowerMockito#mock}, see {@link #mockRealmQuery()}
 * @param returnValue This value will be returned when the query 's RealmResults call {@link RealmResults#iterator()}
 * @param <T> type of object
 * @return mocked {@link RealmResults}
 * @throws Exception
 */
public static <T extends RealmObject> RealmResults<T> initFindAllSorted(RealmQuery<T> query, @Nullable List<T> returnValue) throws Exception {
    RealmResults<T> realmResults = mockRealmResults();
    initLiveRealmResults(realmResults);
    when(query.findAll()).thenReturn(realmResults);
    when(query.findAllSorted(anyString(), any())).thenReturn(realmResults);

    if (returnValue != null) {
        // The for(...) loop in Java needs an iterator, so we're giving it one that has items,
        // since the mock RealmResults does not provide an implementation. Therefore, anytime
        // anyone asks for the RealmResults Iterator, give them a functioning iterator from the
        // ArrayList of Persons we created above. This will allow the loop to execute.
        when(realmResults.size()).thenReturn(returnValue.size());
        when(realmResults.iterator()).thenReturn(returnValue.iterator());
    }
    return realmResults;
}
 
Example #28
Source File: Database.java    From aptoide-client-v8 with GNU General Public License v3.0 4 votes vote down vote up
public <E extends RealmObject> Observable<Long> count(RealmQuery<E> query) {
  return Observable.just(query.count())
      .flatMap(count -> Observable.just(count)
          .unsubscribeOn(RealmSchedulers.getScheduler()))
      .defaultIfEmpty(0L);
}
 
Example #29
Source File: RealmTestUtils.java    From mvvm-template with GNU General Public License v3.0 3 votes vote down vote up
/**
 *
 * Must be run with {@link org.powermock.modules.junit4.PowerMockRunner} or {@link org.robolectric.RobolectricTestRunner}
 * Test classes should be annotated {@link org.powermock.core.classloader.annotations.PrepareForTest}
 * : RealmQuery.class
 *
 * Initialize a mock realm when perform a query. This mock realm will turn a mock {@link RealmQuery}
 * when perform {@link Realm#where(Class)}, and the mock query will return itself when perform {@link RealmQuery#equalTo(String, Long)}
 *
 * @param realm mock realm, should be mocked by {@link PowerMockito#mock(Class)}
 * @param tClass class of realm model
 * @param <T>
 * @return mocked realm query, see {@link #mockRealmQuery()}
 */
public static <T extends RealmObject> RealmQuery<T> initRealmQuery(Realm realm, Class<T> tClass) {
    RealmQuery<T> query = mockRealmQuery();
    when(realm.where(tClass)).thenReturn(query);
    when(query.equalTo(anyString(), anyLong())).thenReturn(query);
    return query;
}
 
Example #30
Source File: RealmTestUtils.java    From mvvm-template with GNU General Public License v3.0 2 votes vote down vote up
/**
 *
 * Must be run with {@link org.powermock.modules.junit4.PowerMockRunner} or {@link org.robolectric.RobolectricTestRunner}
 * Test classes should be annotated {@link org.powermock.core.classloader.annotations.PrepareForTest}
 * : RealmQuery.class
 *
 * @param <T>
 * @return mocked {@link RealmQuery}
 */
@SuppressWarnings("unchecked")
public  static <T extends RealmObject> RealmQuery<T> mockRealmQuery() {
    return mock(RealmQuery.class);
}