io.realm.Realm Java Examples

The following examples show how to use io.realm.Realm. 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: RealmDataService.java    From o2oa with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * 是否常用联系人
 *
 * @param owner
 * @param person
 * @return
 */
public Observable<Boolean> isUsuallyPerson(final String owner, final String person) {
    return RealmObservable.object(new Func1<Realm, Boolean>() {
        @Override
        public Boolean call(Realm realm) {
            String unitId = O2SDKManager.Companion.instance().prefs().getString(O2.INSTANCE.getPRE_BIND_UNIT_ID_KEY(), "");
            RealmResults<UsuallyPersonRealmObject> results = realm
                    .where(UsuallyPersonRealmObject.class).equalTo("owner", owner)
                    .equalTo("person", person).equalTo("unitId", unitId).findAll();
            if (results != null && results.size() > 0) {
                return true;
            }
            return false;
        }
    });
}
 
Example #2
Source File: PopularMoviesApplication.java    From udacity-p1-p2-popular-movies with MIT License 6 votes vote down vote up
@Override
public void onCreate() {
    super.onCreate();

    // initialize the database
    RealmConfiguration.Builder realmConfigurationBuilder = new RealmConfiguration.Builder(this)
            .name(Realm.DEFAULT_REALM_NAME)
            .schemaVersion(DB_SCHEMA_VERSION);
    if (BuildConfig.DEBUG) {
        realmConfigurationBuilder.deleteRealmIfMigrationNeeded();
    }
    RealmConfiguration realmConfiguration = realmConfigurationBuilder.build();
    Realm.setDefaultConfiguration(realmConfiguration);

    // setup the Model so it can listen for and handle requests for data
    // hold a reference to it, to save it from GC
    mModel = new Model();

    enableStrictMode();
}
 
Example #3
Source File: RealmRoomMessageWallet.java    From iGap-Android with GNU Affero General Public License v3.0 6 votes vote down vote up
public static RealmRoomMessageWallet put(final ProtoGlobal.RoomMessageWallet input) {
    Realm realm = Realm.getDefaultInstance();
    RealmRoomMessageWallet messageWallet = null;
    messageWallet = realm.createObject(RealmRoomMessageWallet.class, AppUtils.makeRandomId());

    messageWallet.setType(input.getType().toString());
    messageWallet.setFromUserId(input.getMoneyTransfer().getFromUserId());
    messageWallet.setToUserId(input.getMoneyTransfer().getToUserId());
    messageWallet.setAmount(input.getMoneyTransfer().getAmount());
    messageWallet.setTraceNumber(input.getMoneyTransfer().getTraceNumber());
    messageWallet.setInvoiceNumber(input.getMoneyTransfer().getInvoiceNumber());
    messageWallet.setPayTime(input.getMoneyTransfer().getPayTime());
    messageWallet.setDescription(input.getMoneyTransfer().getDescription());

    realm.close();

    return messageWallet;
}
 
Example #4
Source File: TeamRealm.java    From talk-android with MIT License 6 votes vote down vote up
public void addAndUpdateWithCurrentThread(final Team team) {
    Realm realm = RealmProvider.getInstance();
    try {
        realm.beginTransaction();
        Team realmTeam = realm.where(Team.class).equalTo(Team.ID, team.get_id()).findFirst();
        if (realmTeam == null) {
            realmTeam = realm.createObject(Team.class);
        }
        copy(realmTeam, team);
        realm.commitTransaction();
    } catch (Exception e) {
        e.printStackTrace();
        realm.cancelTransaction();
    } finally {
        realm.close();
    }
}
 
Example #5
Source File: MemberRealm.java    From talk-android with MIT License 6 votes vote down vote up
public List<Member> getNotQuitAndNotRobotMemberWithCurrentThread() {
    final List<Member> members = new ArrayList<>();
    Realm realm = RealmProvider.getInstance();
    try {
        realm.beginTransaction();
        RealmResults<Member> realmResults = realm.where(Member.class)
                .equalTo(Member.TEAM_ID, BizLogic.getTeamId())
                .equalTo(Member.IS_QUIT, false)
                .equalTo(Member.IS_ROBOT, false)
                .findAll();
        realmResults.sort(Member.ALIAS_PINYIN, Sort.ASCENDING);
        for (Member realmResult : realmResults) {
            Member member = new Member();
            copy(member, realmResult);
            members.add(member);
        }
        realm.commitTransaction();
    } catch (Exception e) {
        e.printStackTrace();
        realm.cancelTransaction();
    } finally {
        realm.close();
    }
    return members;
}
 
Example #6
Source File: SaturdayFragment.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","Sat", Case.SENSITIVE).findAll();
        if (studentModuleDao.size()!=0) {

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

        } else {

            b.rvSaturdayTimeTable.setVisibility(View.GONE);
            b.satNoModuleText.setText("You are free today");
            b.satNoModuleText.setVisibility(View.VISIBLE);

        }

//        connectToDataBase();

    }
 
Example #7
Source File: Monarchy.java    From realm-monarchy with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@WorkerThread
@Override
public List<T> loadRange(final int startPosition, final int count) {
    final int countItems = countItems();
    if(countItems == 0) {
        return Collections.emptyList();
    }
    final List<T> list = new ArrayList<>(count);
    monarchy.doWithRealm(new Monarchy.RealmBlock() {
        @Override
        public void doWithRealm(Realm realm) {
            RealmResults<T> results = (RealmResults<T>) monarchy.resultsRefs.get().get(liveResults);
            for(int i = startPosition; i < startPosition + count && i < countItems; i++) {
                // noinspection ConstantConditions
                list.add(realm.copyFromRealm(results.get(i)));
            }
        }
    });

    return Collections.unmodifiableList(list);
}
 
Example #8
Source File: RoomRealm.java    From talk-android with MIT License 6 votes vote down vote up
public Observable<List<Room>> getToJoinRooms() {
    return Observable.create(new OnSubscribeRealm<List<Room>>() {
        @Override
        public List<Room> get(Realm realm) {
            List<Room> rooms = new ArrayList<>();
            RealmResults<Room> realmResults = realm.where(Room.class)
                    .equalTo(Room.TEAM_ID, BizLogic.getTeamId())
                    .equalTo(Room.IS_ARCHIVED, false)
                    .equalTo(Room.IS_QUIT, true)
                    .findAll();
            realmResults.sort(Room.PINYIN, Sort.ASCENDING);
            for (int i = 0; i < realmResults.size(); i++) {
                Room room = new Room();
                copy(room, realmResults.get(i));
                rooms.add(room);
            }
            return rooms;
        }
    });
}
 
Example #9
Source File: RoomRealm.java    From talk-android with MIT License 6 votes vote down vote up
/**
 * 查询所有不是归档的Room
 *
 * @return 查询到的所有数据
 */
public List<Room> getRoomOnNotArchivedWithCurrentThread() {
    List<Room> rooms = new ArrayList<>();
    Realm realm = RealmProvider.getInstance();
    try {
        realm.beginTransaction();
        RealmResults<Room> realmResults = realm.where(Room.class)
                .equalTo(Room.TEAM_ID, BizLogic.getTeamId())
                .equalTo(Room.IS_ARCHIVED, false)
                .findAll();
        realmResults.sort(Room.PINYIN, Sort.ASCENDING);
        for (int i = 0; i < realmResults.size(); i++) {
            Room room = new Room();
            copy(room, realmResults.get(i));
            rooms.add(room);
        }
        realm.commitTransaction();
    } catch (Exception e) {
        e.printStackTrace();
        realm.cancelTransaction();
    } finally {
        realm.close();
    }
    return rooms;
}
 
Example #10
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 #11
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 #12
Source File: Monarchy.java    From realm-monarchy with Apache License 2.0 6 votes vote down vote up
/**
 * Posts the RealmBlock to the Monarchy thread, and executes it there.
 *
 * @param realmBlock the Realm block
 * @throws IllegalStateException if the Monarchy thread is not open
 */
public void postToMonarchyThread(final RealmBlock realmBlock) {
    final Handler _handler = handler.get();
    if(_handler == null) {
        throw new IllegalStateException("Cannot post to Monarchy thread when the Monarchy thread is not open.");
    } else {
        _handler.post(new Runnable() {
            @Override
            public void run() {
                Realm realm = realmThreadLocal.get();
                checkRealmValid(realm);
                realmBlock.doWithRealm(realm);
            }
        });
    }
}
 
Example #13
Source File: PumpHistoryHandler.java    From 600SeriesAndroidUploader with MIT License 6 votes vote down vote up
public void reset() {
    historyRealm.executeTransaction(new Realm.Transaction() {
        @Override
        public void execute(@NonNull Realm realm) {

            int count = 0;
            for (DBitem dBitem : historyDB) {
                RealmResults<PumpHistoryInterface> records = dBitem.results.where().findAll();
                count += records.size();
                records.deleteAllFromRealm();
            }

            Log.d(TAG, "reset history database: deleted " + count + " history records");

            final RealmResults<HistorySegment> segment = historyRealm
                    .where(HistorySegment.class)
                    .findAll();
            segment.deleteAllFromRealm();

            Log.d(TAG, "reset history segments: deleted " + segment.size() + " segment records");
        }
    });
}
 
Example #14
Source File: Stats.java    From 600SeriesAndroidUploader with MIT License 6 votes vote down vote up
public static String report(String key) {
    if (LazyHolder.instance.open > 0) Log.w(TAG, "report called while stats are open [open=" + LazyHolder.instance.open + "]");

    StringBuilder sb = new StringBuilder();

    Class[] classes = STAT_CLASSES;

    Realm storeRealm = Realm.getInstance(UploaderApplication.getStoreConfiguration());

    for (Class clazz : classes) {
        StatInterface record = (StatInterface) storeRealm.where(clazz)
                .equalTo("key", key)
                .findFirst();
        if (record != null) {
            sb.append(sb.length() > 0 ? " [" : "[");
            sb.append(clazz.getSimpleName());
            sb.append("] ");
            sb.append(record.toString());
        }
    }

    storeRealm.close();
    return sb.toString();
}
 
Example #15
Source File: RealmUtil.java    From photosearcher with Apache License 2.0 6 votes vote down vote up
public static void executeTransaction(Action1<Realm> transaction, Action1<Throwable> onFailure) {
    Realm realm = null;

    try {
        realm = Realm.getDefaultInstance();
        realm.beginTransaction();

        transaction.call(realm);

        realm.commitTransaction();
    } catch (Exception e) {
        if (realm != null) {
            realm.cancelTransaction();
        }
        onFailure.call(e);
    } finally {
        if (realm != null) {
            realm.close();
        }
    }
}
 
Example #16
Source File: AssetDefinitionService.java    From alpha-wallet-android with MIT License 6 votes vote down vote up
public String getTokenImageUrl(int networkId, String address)
{
    String url = "";
    String instanceKey = address.toLowerCase() + "-" + networkId;
    try (Realm realm = realmManager.getAuxRealmInstance(IMAGES_DB))
    {
        RealmAuxData instance = realm.where(RealmAuxData.class)
                .equalTo("instanceKey", instanceKey)
                .findFirst();

        if (instance != null)
        {
            url = instance.getResult();
        }
    }
    catch (Exception ex)
    {
        ex.printStackTrace();
    }

    return url;
}
 
Example #17
Source File: SecureUserStoreTests.java    From realm-android-user-store with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws KeyStoreException {
    Realm.init(InstrumentationRegistry.getTargetContext());

    // This will set the 'm_metadata_manager' in 'sync_manager.cpp' to be 'null'
    // causing the SyncUser to remain in memory.
    // They're actually not persisted into disk.
    // move this call to `tearDown` to clean in-memory & on-disk users
    // once https://github.com/realm/realm-object-store/issues/207 is resolved
    TestHelper.resetSyncMetadata();

    RealmConfiguration realmConfig = configFactory.createConfiguration();
    realm = Realm.getInstance(realmConfig);

    userStore = new SecureUserStore(InstrumentationRegistry.getTargetContext());
    assertTrue("KeyStore Should be Unlocked before running tests on device!", userStore.isKeystoreUnlocked());
    SyncManager.setUserStore(userStore);
}
 
Example #18
Source File: RealmRoom.java    From iGap-Android with GNU Affero General Public License v3.0 5 votes vote down vote up
public static boolean isPinedMessage(long roomId, long messageId) {
    boolean result = false;
    Realm realm = Realm.getDefaultInstance();
    RealmRoom room = RealmRoom.getRealmRoom(realm, roomId);
    if (room != null) {
        if (room.getPinMessageId() == messageId) {
            result = true;
        }
    }
    realm.close();
    return result;
}
 
Example #19
Source File: LocalChatBDRealmManager.java    From LazyRecyclerAdapter with MIT License 5 votes vote down vote up
private Observable<Realm> getRealm() {
    return Observable.create(new ObservableOnSubscribe<Realm>() {
        @Override
        public void subscribe(final ObservableEmitter<Realm> emitter)
                throws Exception {
            final Realm observableRealm = Realm.getDefaultInstance();
            emitter.onNext(observableRealm);
            emitter.onComplete();
        }
    });
}
 
Example #20
Source File: UserDao.java    From android-realm-sample with MIT License 5 votes vote down vote up
public void save(final User user) {
    mRealm.executeTransaction(new Realm.Transaction() {
        @Override
        public void execute(Realm realm) {
            realm.copyToRealmOrUpdate(user);
        }
    });
}
 
Example #21
Source File: WalletDataRealmSource.java    From alpha-wallet-android with MIT License 5 votes vote down vote up
public Single<Wallet[]> storeWallets(Wallet[] wallets) {
    return Single.fromCallable(() -> {
        try (Realm realm = realmManager.getWalletDataRealmInstance()) {
            realm.beginTransaction();

            for (Wallet wallet : wallets) {
                RealmWalletData realmWallet = realm.where(RealmWalletData.class)
                        .equalTo("address", wallet.address)
                        .findFirst();

                if (realmWallet == null) {
                    realmWallet = realm.createObject(RealmWalletData.class, wallet.address);
                    realmWallet.setENSName(wallet.ENSname);
                    realmWallet.setBalance(wallet.balance);
                    realmWallet.setName(wallet.name);
                } else {
                    if (realmWallet.getBalance() == null || !wallet.balance.equals(realmWallet.getENSName()))
                        realmWallet.setBalance(wallet.balance);
                    if (wallet.ENSname != null && (realmWallet.getENSName() == null || !wallet.ENSname.equals(realmWallet.getENSName())))
                        realmWallet.setENSName(wallet.ENSname);
                    realmWallet.setName(wallet.name);
                }
            }
            realm.commitTransaction();
        } catch (Exception e) {
            Log.e(TAG, "storeWallets: " + e.getMessage(), e);
        }
        return wallets;
    });
}
 
Example #22
Source File: LinksPresenterImpl.java    From redgram-for-reddit with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void enableNsfwPreview() {
    Realm realm = linksView.getContentContext().getBaseActivity().getRealm();
    if(realm != null){
        realm.executeTransaction(instance -> getPrefs().setDisableNsfwPreview(false));
    }
}
 
Example #23
Source File: ViewerActivity.java    From GankMeizhi with Apache License 2.0 5 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    supportPostponeEnterTransition();

    setContentView(R.layout.activity_viewer);
    ButterKnife.bind(this);

    index = getIntent().getIntExtra("index", 0);

    realm = Realm.getDefaultInstance();
    realm.addChangeListener(this);

    images = Image.all(realm);

    puller.setCallback(this);

    adapter = new PagerAdapter();

    pager.setAdapter(adapter);
    pager.setCurrentItem(index);

    // 避免图片在进行 Shared Element Transition 时盖过 Toolbar
    if (Build.VERSION.SDK_INT >= 21) {
        getWindow().setSharedElementsUseOverlay(false);
    }

    setEnterSharedElementCallback(new SharedElementCallback() {
        @Override
        public void onMapSharedElements(List<String> names, Map<String, View> sharedElements) {
            Image image = images.get(pager.getCurrentItem());
            sharedElements.clear();
            sharedElements.put(image.getUrl(), adapter.getCurrent().getSharedElement());
        }
    });
}
 
Example #24
Source File: RealmRoomMessage.java    From iGap-Android with GNU Affero General Public License v3.0 5 votes vote down vote up
public static RealmRoomMessage findLastMessage(Realm realm, long roomId) {
    //TODO [Saeed Mozaffari] [2017-10-23 11:24 AM] - Can Write Better Code?
    RealmResults<RealmRoomMessage> realmRoomMessages = findDescending(realm, roomId);
    RealmRoomMessage realmRoomMessage = null;
    if (realmRoomMessages.size() > 0) {
        realmRoomMessage = realmRoomMessages.first();
    }
    return realmRoomMessage;
}
 
Example #25
Source File: RealmChannelRoom.java    From iGap-Android with GNU Affero General Public License v3.0 5 votes vote down vote up
public static ProtoGlobal.ChannelRoom.Role detectMineRole(long roomId) {
    ProtoGlobal.ChannelRoom.Role role = ProtoGlobal.ChannelRoom.Role.UNRECOGNIZED;
    Realm realm = Realm.getDefaultInstance();
    RealmRoom realmRoom = realm.where(RealmRoom.class).equalTo(RealmRoomFields.ID, roomId).findFirst();
    if (realmRoom != null) {
        RealmChannelRoom realmChannelRoom = realmRoom.getChannelRoom();
        if (realmChannelRoom != null) {
            role = realmChannelRoom.getMainRole();
        }
    }
    realm.close();
    return role;
}
 
Example #26
Source File: RoomRealm.java    From talk-android with MIT License 5 votes vote down vote up
public Observable<Room> archive(final Room room) {
    return Observable.create(new OnSubscribeRealm<Room>() {
        @Override
        public Room get(Realm realm) {
            Room realmRoom = realm.where(Room.class)
                    .equalTo(Room.TEAM_ID, BizLogic.getTeamId())
                    .equalTo(Room.ID, room.get_id())
                    .findFirst();
            if (realmRoom == null) return null;
            realmRoom.setIsArchived(true);
            return room;
        }
    }).subscribeOn(Schedulers.io());
}
 
Example #27
Source File: PerfTestRealm.java    From android-database-performance with Apache License 2.0 5 votes vote down vote up
protected void createRealm() {
    Realm.init(getTargetContext());
    RealmConfiguration.Builder configBuilder = new RealmConfiguration.Builder();
    if (inMemory) {
        configBuilder.name("inmemory.realm").inMemory();
    } else {
        configBuilder.name("ondisk.realm");
    }
    realm = Realm.getInstance(configBuilder.build());
}
 
Example #28
Source File: RealmOfflineSeen.java    From iGap-Android with GNU Affero General Public License v3.0 5 votes vote down vote up
public static RealmOfflineSeen put(Realm realm, long messageId) {
    RealmOfflineSeen realmOfflineSeen = realm.createObject(RealmOfflineSeen.class, SUID.id().get());
    realmOfflineSeen.setOfflineSeen(messageId);
    realm.copyToRealmOrUpdate(realmOfflineSeen);

    return realmOfflineSeen;
}
 
Example #29
Source File: Database.java    From udacity-p1-p2-popular-movies with MIT License 5 votes vote down vote up
private void write(@NonNull final Realm.Transaction transaction,
                   @NonNull final WriteCallback writeCallback) {
    Realm realm = null;
    try {
        realm = Realm.getDefaultInstance();
        realm.executeTransaction(transaction, writeCallback);
    } finally {
        if (realm != null) {
            realm.close();
        }
    }
}
 
Example #30
Source File: UserDaoTest.java    From android-realm-sample with MIT License 5 votes vote down vote up
@Override
protected void setUp() throws Exception {
    super.setUp();

    Context context = getInstrumentation().getTargetContext();
    RealmConfiguration realmConfiguration = new RealmConfiguration.Builder(context).build();
    Realm.setDefaultConfiguration(realmConfiguration);

    mRealm = RealmManager.open();
    RealmManager.clear();
}