Java 类io.realm.Realm 实例源码

项目:store2realm    文件:RealmDao.java   
/**
 * Get one with a specific filter object
 * @param filter
 * @return
 */
@Override
public Flowable<Optional<T>> getOne(Filter filter, SortingMode sortingMode) {
    Realm realm = Realm.getDefaultInstance();
    RealmQuery<T> query = realm.where(clazz);
    query = filterToQuery(filter, query);
    T item = null;
    if (sortingMode != null) {
        RealmResults<T> items = applySortingMode(sortingMode, query);
        if (!items.isEmpty()) {
            item = items.first();
        }
    } else {
        item = query.findFirst();
    }
    T copy = null;
    if (item != null) {
        copy = realm.copyFromRealm(item);
    }
    realm.close();
    return Flowable.just(Optional.wrap(copy));
}
项目:stetho-realm    文件:App.java   
private void populateRealm() {
    final Realm realm = Realm.getDefaultInstance();

    final Author moses = new Author();
    moses.name = "Moses";
    final Book genesis = new Book();
    genesis.index = 0;
    genesis.name = "Genesis";
    genesis.author = moses;
    final Book exodus = new Book();
    exodus.index = 1;
    exodus.name = "Exodus";
    exodus.author = moses;
    final Book hebrews = new Book();
    hebrews.index = 57;
    hebrews.name = "Letter to the Hebrews";

    realm.beginTransaction();
    realm.copyToRealmOrUpdate(genesis);
    realm.copyToRealmOrUpdate(exodus);
    realm.copyToRealmOrUpdate(hebrews);
    realm.commitTransaction();

    realm.close();
}
项目:Espresso    文件:CompaniesLocalDataSource.java   
@Override
public Observable<List<Company>> searchCompanies(@NonNull String keyWords) {
    Realm rlm = RealmHelper.newRealmInstance();
    List<Company> results = rlm.copyFromRealm(
            rlm.where(Company.class)
                    .like("name","*" + keyWords + "*", Case.INSENSITIVE)
                    .or()
                    .like("tel", "*" + keyWords + "*", Case.INSENSITIVE)
                    .or()
                    .like("website", "*" + keyWords + "*", Case.INSENSITIVE)
                    .or()
                    .like("alphabet", "*" + keyWords + "*", Case.INSENSITIVE)
                    .findAllSorted("alphabet", Sort.ASCENDING));
    return Observable.fromIterable(results)
            .toList()
            .toObservable();
}
项目:Programmers    文件:PostsLocalDataSource.java   
@Override
public void getByUser(String authorId, Callbacks.IResultsCallback<Post> callback) {
    Realm realm = Realm.getDefaultInstance();

    try {
        List<Post> result = realm
                .where(Post.class)
                .equalTo("authorId", authorId) // Fetch posts by author id
                .findAll();

        if (result == null || result.isEmpty()) {
            callback.onDataUnavailable();
            return;
        }

        // Retrieve the data
        callback.onSuccess(result);
    } catch (Exception ex) {
        ex.printStackTrace();
        callback.onDataUnavailable();
    }
}
项目:WatchIt    文件:NotificationPublisher.java   
private Movie fetchRandomMovieOrTvSeries() {
    Realm realm = Realm.getDefaultInstance();
    //TODO: Add Random TV Series to fetch
    RealmResults<Movie> movieRealmResults = realm.where(Movie.class).equalTo("isNotified", false).findAll();

    Util.debugLog(TAG, "fetchRandomMovieOrTvSeries: Size of movies with isNotified false " + movieRealmResults.size());

    if (movieRealmResults.size() != 0) {

        Random r = new Random();
        int randomNumber = r.nextInt(movieRealmResults.size());

        Movie movie = movieRealmResults.get(randomNumber);

        realm.beginTransaction();
        movieRealmResults.get(randomNumber).setNotified(true);
        realm.commitTransaction();


        return movie;
    } else {
        return null;
    }
}
项目:INFOotball    文件:RealmManager.java   
@Override
@NonNull
public String getBadgeUrl(String idTeam){
    try(Realm realm = realmProvider.get()){
        TeamRealm teamRealm = realm.where(TeamRealm.class).equalTo("idTeam",idTeam).findFirst();
        if(teamRealm != null){
            if(teamRealm.getStrTeamBadge() != null && ! teamRealm.getStrTeamBadge().isEmpty())
                return teamRealm.getStrTeamBadge();
            else if(teamRealm.getStrTeamLogo() != null && ! teamRealm.getStrTeamLogo().isEmpty())
                return teamRealm.getStrTeamLogo();
            else if(teamRealm.getStrTeamJersey() != null && ! teamRealm.getStrTeamJersey().isEmpty())
                return teamRealm.getStrTeamJersey();
        }
        return "http://www.wunapps.com/2015/lg/padres_lg/images/lg-team-badge-08.png";
    }
}
项目:Cluttr    文件:MediaLoader.java   
public static void updateCoverPhotos() {
    long time = System.currentTimeMillis();
    Realm realm = Realm.getDefaultInstance();
    realm.beginTransaction();
    for (Album a : realm.where(Album.class).findAll()) {
        switch (Media.getMediaSortType()) {
            case ALPHABETICAL: {
                a.setCoverPath(a.getMedia().sort("name", Media.isMediaSortAscending() ? Sort.ASCENDING : Sort.DESCENDING).first().getPath());
                break;
            }
            case DATE: {
                a.setCoverPath(a.getMedia().sort("date", Media.isMediaSortAscending() ? Sort.ASCENDING : Sort.DESCENDING).first().getPath());
                break;
            }
        }
    }
    realm.commitTransaction();
    realm.close();
    Log.d(Util.LOG_TAG, "Reloading all cover photos took " + (System.currentTimeMillis() - time));
}
项目:face-landmark-android    文件:ARFaceFragment.java   
private void initRealm() {
    realm = Realm.getDefaultInstance();
    realmResults = realm.where(ImageBean.class).equalTo("hasFace", true).findAllAsync();
    realmResults.addChangeListener(new RealmChangeListener<RealmResults<ImageBean>>() {
        @Override
        public void onChange(RealmResults<ImageBean> results) {
            if (results.size() > 0) {
                Log.e(TAG, "results size: " + results.size());
                mTvSearchHint.setVisibility(View.GONE);
                mImages.clear();
                mImages.addAll(results.subList(0, results.size()));
                if (mFaceAdapter != null) {
                    mFaceAdapter.notifyDataSetChanged();
                    Log.e(TAG, "getItemCount: " + mFaceAdapter.getItemCount());
                }
            } else {
                mTvSearchHint.setVisibility(View.VISIBLE);
            }
        }
    });
}
项目:Slide-RSS    文件:UserFeeds.java   
public static void setFeeds(final ArrayList<FeedWrapper> subs) {
    Realm.getDefaultInstance().executeTransaction(new Realm.Transaction() {
        @Override
        public void execute(Realm realm) {
            for (int i = 0; i < subs.size(); i++) {
                subs.get(i).setOrder(i);
            }
            for (FeedWrapper f : subs) {
                if(f instanceof Feed){
                    realm.insertOrUpdate((Feed)f);
                } else {
                    realm.insertOrUpdate((Category)f);
                }
            }
        }
    });
}
项目:Slide-RSS    文件:ReorderFeeds.java   
@Override
protected void onPostExecute(final Feed feed) {
    if (feed != null) {
        new AlertDialogWrapper.Builder(ReorderFeeds.this).setTitle("Feed added successfully!").setPositiveButton("Ok!", null).show();
        Realm.getDefaultInstance().executeTransactionAsync(new Realm.Transaction() {
            @Override
            public void execute(Realm realm) {
                realm.copyToRealmOrUpdate(feed);
            }
        }, new Realm.Transaction.OnSuccess() {
            @Override
            public void onSuccess() {
                doAddSub(feed);
            }
        });
    } else {
        new SearchSiteTask().execute(url);
    }
}
项目:stetho-realm    文件:App.java   
@Override
public void onCreate() {
    super.onCreate();

    Realm.init(this);
    Stetho.initialize(Stetho.newInitializerBuilder(this)
        .enableDumpapp(Stetho.defaultDumperPluginsProvider(this))
        .enableWebKitInspector(
            new StethoRealmInspectorModulesProvider.Builder(this).dirs(getFilesDir(),
                new File(getFilesDir(), "custom")).build())
        .build());

    populateRealm();
    populateRealm2();
    populateRealmIgnored();
}
项目:Programmers    文件:PostsLocalDataSource.java   
@Override
public void getById(String postId, Callbacks.IResultCallback<Post> callback) {
    Realm realm = Realm.getDefaultInstance();

    try {
        //Return the first item tha id match with postId
        Post result = realm
                .where(Post.class)
                .equalTo("id", postId)
                .findFirst();

        // Check if there is a valid data
        if (result == null) {
            callback.onDataUnavailable();
            return;
        }

        // Return the data
        callback.onSuccess(result);
    } catch (Exception ex) {
        ex.printStackTrace();
        callback.onDataUnavailable();
    }
}
项目:yyox    文件:UserSettingActivity.java   
public void btn_logout_click(View v) {
    RealmConfiguration config = new RealmConfiguration.Builder().name("yyox.realm").build();
    Realm objRealm = Realm.getInstance(config);

    //查找
    RealmUser realmUser = objRealm.where(RealmUser.class).findFirst();
    if (realmUser != null) {
        //先删除
        objRealm.beginTransaction();
        RealmResults results = objRealm.where(RealmUser.class).findAll();
        results.deleteAllFromRealm();
        objRealm.commitTransaction();

    }
    mPresenter.requestLogout(this);
    WEApplication weApplication = (WEApplication) getApplication();
    weApplication.setRealmUser(null);

    Intent intent = new Intent();
    setResult(CodeDefine.SETTING_RESULT, intent);
}
项目:GitHub    文件:ProcessCommitTests.java   
@Override
protected void run() {
    user = UserFactory.getInstance().loginWithDefaultUser(Constants.AUTH_URL);
    String realmUrl = Constants.SYNC_SERVER_URL;

    final SyncConfiguration syncConfig = new SyncConfiguration.Builder(user, realmUrl)
            .directory(getService().getRoot())
            .build();
    getService().setRealm(Realm.getInstance(syncConfig));
    Realm realm = getService().getRealm();

    realm.beginTransaction();
    ProcessInfo processInfo = realm.createObject(ProcessInfo.class);
    processInfo.setName("Background_Process1");
    processInfo.setPid(android.os.Process.myPid());
    processInfo.setThreadId(Thread.currentThread().getId());
    realm.commitTransaction();
    // FIXME: If we close the Realm here, the data won't be able to synced to the main process. Is it a bug
    // in sync client which stops too early?
    // Realm is currently configured with stop_immediately. This means the sync session is closed as soon as
    // the last realm instance is closed. Not doing this would make the Realm lifecycle really
    // unpredictable. We should have an easy way to wait for all changes to be uploaded though.
    // Perhaps SyncSession.uploadAllLocalChanges() or something similar to
    // SyncSesson.downloadAllServerChanges()
}
项目:GitHub    文件:MainActivity.java   
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    textView = (TextView) findViewById(R.id.textView);

    if (realm == null) {
        realm = Realm.getDefaultInstance();
        processInfoResults = realm.where(ProcessInfo.class).findAllAsync();
        processInfoResults.addChangeListener(listener);
    }

    realm.beginTransaction();
    realm.copyToRealmOrUpdate(Utils.createStandaloneProcessInfo(this));
    realm.commitTransaction();
}
项目:AlarmWithL-T    文件:FormActivity.java   
@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Check NightMode On/Off
        mConfig = getSharedPreferences(getString(R.string.key_config), MODE_PRIVATE);
        boolean isNightMode = mConfig.getBoolean(getString(R.string.key_is_night_mode), false);
        if (isNightMode) {
            setTheme(R.style.DarkTheme);
        } else {
            setTheme(R.style.LightTheme);
        }

        checkPermission();

        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_new_create);  //Binding Layout
        initToolbar();

        FragmentTransaction transaction = getFragmentManager().beginTransaction();
        mFragment = SettingFragment.newInstance();
        transaction.add(R.id.setting_fragment, mFragment);
        transaction.commit();

        mRealm = Realm.getDefaultInstance(); // Initialize Realm
//        Intent intent = getIntent();
//       if (intent.getStringExtra("data") != null) {
//            Bundle bundle = new Bundle();
//            bundle.putString("data", intent.getStringExtra("data"));
//            mFragment.setArguments(bundle);
//            if (intent.getStringExtra(getString(R.string.key_title)) != null) {
//                mFragment.setArguments(intent.getExtras());
//            }
//        }
    }
项目:GitHub    文件:WakefulReceivingService.java   
@Override
protected void onHandleIntent(Intent intent) {
    if (intent.getExtras() != null) {
        String personId = intent.getStringExtra("person_id");
        Realm realm = Realm.getDefaultInstance();
        Person person = realm.where(Person.class).equalTo("id", personId).findFirst();
        final String output = person.toString();
        new Handler(getMainLooper()).post(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(getApplicationContext(), "Loaded Person from broadcast-receiver->intent-service: " + output, Toast.LENGTH_LONG).show();
            }
        });
        realm.close();
    }

    // All the work is done, release the wake locks/etc
    WakefulBroadcastReceiver.completeWakefulIntent(intent);
}
项目:ElephantAsia    文件:RealmDB.java   
static public void insertOrUpdateElephant(final Elephant elephant, final List<Document> documents) {
    Realm realm = Realm.getDefaultInstance();
    realm.executeTransactionAsync(new Realm.Transaction() {
        @Override
        public void execute(Realm bgRealm) {
            if (elephant.id == -1) {
                elephant.id = getNextId(bgRealm, Elephant.class, Elephant.ID);
            }
            bgRealm.insertOrUpdate(elephant);

            for (Document document : documents) {
                if (document.id == -1) {
                    document.id = getNextId(bgRealm, Document.class, Document.ID);
                }
                document.elephant_id = elephant.id;
                bgRealm.insertOrUpdate(document);
            }
        }
    });
}
项目:Android-Client    文件:LoginTask.java   
@Override
protected Void parse(JSONObject jsonObject) throws JSONException {

    UserData.getInstance()
            .setEnteredEmail(email)
            .setHashedPassowrd(hashedPassword)
            .updateFromJson(jsonObject);

    //Sync filters
    final JSONArray filtersJsonArray = jsonObject.getJSONArray("filters");

    RealmWrites.withDefaultRealm().executeTransaction(new RealmWrites.Transaction<Void>() {
        @Override
        public Void execute(Realm realm) {
            try {
                RealmSyncs.withRealm(realm).syncFilters(filtersJsonArray);
            } catch (JSONException e) {
                Log.d(TAG, "Error syncing filters", e);
            }

            return null;
        }
    });

    return null;
}
项目:INFOotball    文件:RealmManager.java   
@Override
@NonNull
public String getJerseyUrl(String idTeam){
    try(Realm realm = realmProvider.get()){
        TeamRealm teamRealm = realm.where(TeamRealm.class).equalTo("idTeam",idTeam).findFirst();
        if(teamRealm != null){
            if(teamRealm.getStrTeamJersey() != null && ! teamRealm.getStrTeamJersey().isEmpty())
                return teamRealm.getStrTeamJersey();
            else if(teamRealm.getStrTeamBadge() != null && ! teamRealm.getStrTeamBadge().isEmpty())
                return teamRealm.getStrTeamBadge();
            else if(teamRealm.getStrTeamLogo() != null && ! teamRealm.getStrTeamLogo().isEmpty())
                return teamRealm.getStrTeamLogo();
        }
    }
    return "https://fm-view.net/forum/uploads/monthly_2017_09/NO-BRAND-73.png.cf70c74cd066c59d9ce14992f0bdedfc.png";
}
项目:realm-helpers    文件:RealmPaginationManager.java   
public void open() {
    if(openCount.getAndIncrement() == 0) {
        HandlerThread handlerThread = new HandlerThread("REALM_PAGINATION_THREAD[" + hashCode() + "]");
        this.handlerThread.set(handlerThread);
        //noinspection SynchronizationOnLocalVariableOrMethodParameter
        synchronized(handlerThread) {
            handlerThread.start();
            try {
                handlerThread.wait();
            } catch(InterruptedException e) {
                // Ignored
            }
        }
        Handler handler = new Handler(handlerThread.getLooper());
        this.handler.set(handler);
        this.queryExecutor.set(new RealmQueryExecutor(this, handler));
        handler.post(() -> {
            workerRealm.set(Realm.getDefaultInstance()); // TODO: Support other configurations.
        });
    }
}
项目:Neuronizer    文件:NoteRepositoryImpl.java   
@Override
public List<Note> getAll() {
    Realm realm = Realm.getInstance(configuration);
    RealmResults<NoteDAO> noteDAOs = realm.where(NoteDAO.class).findAll();
    List<Note> notes = new ArrayList<>(noteDAOs.size());
    for (NoteDAO dao : noteDAOs) {
        notes.add(RealmConverter.convert(dao));
    }
    realm.close();
    return notes;
}
项目:GitHub    文件:RunInLooperThread.java   
/**
 * Get the test realm.
 * <p>
 * Set on test thread, accessed from main thread.
 * Valid only after the test thread has started.
 *
 * @return the test realm.
 */
public Realm getRealm() {
    synchronized (lock) {
        while (backgroundHandler == null) {
            try {
                lock.wait(WAIT_TIMEOUT_MS);
            } catch (InterruptedException ignore) {
                break;
            }
        }
        return realm;
    }
}
项目:smart-asset-iot-android-demo    文件:DataBaseHelper.java   
public void insertDevice(RegisterData registerData) {
    try (Realm realm = Realm.getDefaultInstance()) {
        realm.executeTransaction(t -> {
            String id = registerData.getDeviceId();
            DeviceModel newModel = new DeviceModel();
            newModel.setId(DeviceModel.DEFAULT_ID);
            newModel.setDeviceId(id);
            newModel.setName(newModel.getName());
            newModel.setDeviceName(createDeviceName(id));
            t.copyToRealmOrUpdate(newModel);
        });
    }
}
项目:smart-asset-iot-android-demo    文件:DataBaseHelper.java   
public String getDeviceName() {
    try (Realm realm = Realm.getDefaultInstance()) {
        DeviceModel model = realm.where(DeviceModel.class)
                .equalTo(DeviceModel.ID,
                        DeviceModel.DEFAULT_ID).findFirst();
        if (model == null) {
            return null;
        } else {
            return model.getDeviceName();
        }
    }
}
项目:RxRealm    文件:RxRealm.java   
private static <T extends RealmObject> Observable<RealmResults<T>> listenRealmResults(
        final Func1<Realm, RealmResults<T>> query, AtomicReference<Realm> realmReference) {
    final HandlerThread dbHandler = createDbHandler();
    final Scheduler scheduler = AndroidSchedulers.from(dbHandler.getLooper());
    return Observable.defer(() -> {
        final Realm realm = Realm.getDefaultInstance();
        realmReference.set(realm);
        return query.call(realm).asObservable();
    })
            .filter(result -> result.isLoaded() && result.isValid())
            .subscribeOn(scheduler)
            .unsubscribeOn(scheduler);
}
项目:Cluttr    文件:Media.java   
public static List<String> albumsNeedReloaded() {
    List<String> reloads = new ArrayList<>();
    Realm realm = Realm.getDefaultInstance();
    for (Album a : realm.where(Album.class).findAll()) {
        if (a.needsReload()) {
            reloads.add(a.getPath());
        }
    }
    return reloads;
}
项目:GeekZone    文件:RealmDBHelper.java   
@Override
public void unlikeZhiHuColumnAuthor(final String authorHref) {
    mRealm.executeTransactionAsync(new Realm.Transaction() {
        @Override
        public void execute(Realm realm) {
            RealmResults<LikeArticleBean> results = realm.where(LikeArticleBean.class)
                    .equalTo(LikeArticleFieldMap.AUTHORHREF, authorHref).findAll();
            if (results != null && !results.isEmpty() && results.isValid()) {
                results.deleteAllFromRealm();
            }
        }
    });
}
项目:Espresso    文件:WidgetListFactory.java   
@Override
public int getCount() {
    return Realm.getInstance(new RealmConfiguration.Builder()
            .deleteRealmIfMigrationNeeded()
            .name(DATABASE_NAME)
            .build())
            .where(Package.class)
            .notEqualTo("state", String.valueOf(Package.STATUS_DELIVERED))
            .findAllSorted("timestamp", Sort.DESCENDING)
            .size();
}
项目:TrackIt-Android    文件:RealmSingleton.java   
private RealmSingleton() {
    try {
        realm = Realm.getDefaultInstance();
    } catch (Exception e) {
        RealmConfiguration config = new RealmConfiguration.Builder(App.getAppContext())
                .name("tmsdb.realm")
                .schemaVersion(REALM_SCHEMA_VERSION)
                .migration(new MyRealmMigration())
                .build();
        Realm.setDefaultConfiguration(config);
        realm = Realm.getDefaultInstance();
    }
}
项目:realm-helpers    文件:RealmManager.java   
/**
 * Opens a reference-counted local Realm instance.
 *
 * @return the open Realm instance
 */
public Realm openLocalInstance() {
    checkDefaultConfiguration();
    Realm realm = Realm.getDefaultInstance(); // <-- consider adding parameter and Map<RealmConfiguration, ...>
    Realm localRealm = localRealms.get();
    if(localRealm == null || localRealm.isClosed()) {
        localRealms.set(realm);
    }
    return realm;
}
项目:schulcloud-mobile-android    文件:DatabaseHelper.java   
/**** News ****/
public Observable<List<News>> getNews() {
    final Realm realm = mRealmProvider.get();
    return realm.where(News.class).findAllAsync().asObservable()
            .filter(news -> news.isLoaded())
            .map(news -> {
                List<News> newsList = realm.copyFromRealm(news);
                Collections.sort(newsList, (o1, o2) -> o2.createdAt.compareTo(o1.createdAt));
                return newsList;
            });
}
项目:SOS-The-Healthcare-Companion    文件:DatabaseHandler.java   
public Realm getNewRealmInstance() {
    if (mRealmConfig == null) {
        mRealmConfig = new RealmConfiguration.Builder(mContext)
                .schemaVersion(4)
                .build();
    }
    return Realm.getInstance(mRealmConfig); // Automatically run migration if needed
}
项目:Espresso    文件:App.java   
@Override
public void onCreate() {
    super.onCreate();
    Realm.init(this);

    if (PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).getBoolean(SettingsUtil.KEY_NIGHT_MODE, false)) {
        AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
    } else {
        AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
    }
}
项目:multi-copy    文件:NotesFragment.java   
@Override
public void onNewNote(String note,String createdAt) {
    if (notesFragment_LOG)
    Log.d(TAG, "onNewNote: " + note  +  " " + createdAt);
    Realm realm = Realm.getDefaultInstance();
    realm.beginTransaction();
    notesList.add(new NotesModel(note,createdAt));
    realm.copyToRealmOrUpdate(notesList);
    realm.commitTransaction();
    notesAdapter.notifyDataSetChanged();
}
项目:kyandroid    文件:LocalData.java   
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();
}
项目:ElephantAsia    文件:EditElephantActivity.java   
@Override
protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.add_elephant_activity);
  ButterKnife.bind(this);

  rootView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
    @Override
    public void onGlobalLayout() {
      boolean keyboardIsUp = KeyboardHelpers.keyboardIsDisplay(rootView);

      if (keyboardIsUp) {
        fab.hide();
      } else {
        fab.show();
      }
    }
  });

  setSupportActionBar(toolbar);
  if (getSupportActionBar() != null) {
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
  }

  setupViewPager(viewPager);
  tabLayout.setupWithViewPager(viewPager);
  realm = Realm.getDefaultInstance();

  Integer id = getIntent().getIntExtra(EXTRA_EDIT_ELEPHANT_ID, -1);
if (id == -1) {
    throw new RuntimeException("EditElephantActivity:141: incorrect ID");
}
  elephant = realm.copyFromRealm(realm.where(Elephant.class).equalTo(ID, id).findFirst());
documents = realm.copyFromRealm(realm.where(Document.class).equalTo(Document.ELEPHANT_ID, id).findAll());

  toolbarTitle.setText(String.format(getString(R.string.edit_elephant_title), elephant.name));
docFragment.addDocuments(documents);
}
项目:GitHub    文件:RealmHelper.java   
@Inject
public RealmHelper() {
    mRealm = Realm.getInstance(new RealmConfiguration.Builder()
            .deleteRealmIfMigrationNeeded()
            .name(DB_NAME)
            .build());
}
项目:Crypto-Assistant    文件:MainActivity.java   
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    realm=Realm.getDefaultInstance();
    navigation= (BottomNavigationView) findViewById(R.id.navigation);
    navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
    navigation.setSelectedItemId(R.id.navigation_dashboard);

}
项目:trust-wallet-android    文件:RealmTokenSource.java   
@Override
public Single<TokenInfo[]> fetch(NetworkInfo networkInfo, Wallet wallet) {
    return Single.fromCallable(() -> {
        Realm realm = null;
        try {
            realm = getRealmInstance(networkInfo, wallet);
            RealmResults<RealmTokenInfo> realmItems = realm.where(RealmTokenInfo.class)
                    .sort("addedTime", Sort.ASCENDING)
                    .findAll();
            int len = realmItems.size();
            TokenInfo[] result = new TokenInfo[len];
            for (int i = 0; i < len; i++) {
                RealmTokenInfo realmItem = realmItems.get(i);
                if (realmItem != null) {
                    result[i] = new TokenInfo(
                            realmItem.getAddress(),
                            realmItem.getName(),
                            realmItem.getSymbol(),
                            realmItem.getDecimals());
                }
            }
            return result;
        } finally {
            if (realm != null) {
                realm.close();
            }
        }
    });
}