Java Code Examples for io.realm.Realm#getDefaultInstance()

The following examples show how to use io.realm.Realm#getDefaultInstance() . 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: HelperUrl.java    From iGap-Android with GNU Affero General Public License v3.0 6 votes vote down vote up
private static void goToChat(final ProtoGlobal.RegisteredUser user, final ChatEntry chatEntery, long messageId) {

        Long id = user.getId();

        Realm realm = Realm.getDefaultInstance();
        RealmRoom realmRoom = realm.where(RealmRoom.class).equalTo(RealmRoomFields.CHAT_ROOM.PEER_ID, id).equalTo(RealmRoomFields.IS_DELETED, false).findFirst();

        if (realmRoom != null) {
            closeDialogWaiting();

            goToActivity(realmRoom.getId(), id, user.getBot() ? ChatEntry.chat : chatEntery, messageId);

            realm.close();
        } else {
            if (G.userLogin) {
                addChatToDatabaseAndGoToChat(user, -1, user.getBot() ? ChatEntry.chat : chatEntery);
            } else {
                closeDialogWaiting();
                HelperError.showSnackMessage(G.context.getString(R.string.there_is_no_connection_to_server), false);
            }
        }
    }
 
Example 2
Source File: RealmChannelRoom.java    From iGap-Android with GNU Affero General Public License v3.0 6 votes vote down vote up
public static ProtoGlobal.ChannelRoom.Role detectMemberRoleServerEnum(long roomId, long messageSenderId) {
    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) {
        if (realmRoom.getChannelRoom() != null) {
            RealmList<RealmMember> realmMembers = realmRoom.getChannelRoom().getMembers();
            for (RealmMember realmMember : realmMembers) {
                if (realmMember.getPeerId() == messageSenderId) {
                    role = ProtoGlobal.ChannelRoom.Role.valueOf(realmMember.getRole());
                }
            }
        }
    }
    realm.close();
    return role;
}
 
Example 3
Source File: RealmExecutor.java    From android-orm-benchmark-updated with Apache License 2.0 6 votes vote down vote up
@Override
public long dropDb() throws SQLException
{
    long start = System.nanoTime();

    final Realm realm = Realm.getDefaultInstance();

    try
    {
        realm.beginTransaction();
        realm.deleteAll();
    }
    finally
    {
        realm.commitTransaction();
        realm.close();
    }

    return System.nanoTime() - start;
}
 
Example 4
Source File: RealmUserInfo.java    From iGap-Android with GNU Affero General Public License v3.0 5 votes vote down vote up
public static void updateEmail(final String email) {
    Realm realm1 = Realm.getDefaultInstance();
    realm1.executeTransaction(new Realm.Transaction() {
        @Override
        public void execute(Realm realm) {
            RealmUserInfo realmUserInfo = realm.where(RealmUserInfo.class).findFirst();
            if (realmUserInfo != null) {
                realmUserInfo.setEmail(email);
            }
        }
    });
    realm1.close();
}
 
Example 5
Source File: RecyclerViewExampleActivity.java    From realm-android-adapters with Apache License 2.0 5 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_recyclerview);
    realm = Realm.getDefaultInstance();
    recyclerView = findViewById(R.id.recycler_view);
    setUpRecyclerView();
}
 
Example 6
Source File: PumpHistoryHandler.java    From 600SeriesAndroidUploader with MIT License 5 votes vote down vote up
private void init() {
    Log.d(TAG, "initialise history handler");

    realm = Realm.getDefaultInstance();
    storeRealm = Realm.getInstance(UploaderApplication.getStoreConfiguration());
    dataStore = storeRealm.where(DataStore.class).findFirst();

    historyRealm = Realm.getInstance(UploaderApplication.getHistoryConfiguration());

    historyDB = new ArrayList<>();
    historyDB.add(new DBitem(PumpHistoryCGM.class));
    historyDB.add(new DBitem(PumpHistoryBolus.class));
    historyDB.add(new DBitem(PumpHistoryBasal.class));
    historyDB.add(new DBitem(PumpHistoryPattern.class));
    historyDB.add(new DBitem(PumpHistoryBG.class));
    historyDB.add(new DBitem(PumpHistoryProfile.class));
    historyDB.add(new DBitem(PumpHistoryMisc.class));
    historyDB.add(new DBitem(PumpHistoryMarker.class));
    historyDB.add(new DBitem(PumpHistoryLoop.class));
    historyDB.add(new DBitem(PumpHistoryDaily.class));
    historyDB.add(new DBitem(PumpHistoryAlarm.class));
    historyDB.add(new DBitem(PumpHistorySystem.class));

    pumpHistorySender = new PumpHistorySender().buildSenders(dataStore);

    Stats.open();
}
 
Example 7
Source File: CreateNewTaskActivity.java    From citrus with Apache License 2.0 5 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_create_new_task);
    ButterKnife.bind(this);
    Toolbar toolbar = findById(this, R.id.toolbar);
    setSupportActionBar(toolbar);
    ActionBar actionBar = getSupportActionBar();
    if (actionBar != null) {
        actionBar.setDisplayShowTitleEnabled(false);
        actionBar.setDisplayHomeAsUpEnabled(true);
    }

    mTaskNameEditText.setOnKeyListener(new View.OnKeyListener() {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if (event.getAction() == KeyEvent.ACTION_DOWN
                    && keyCode == KeyEvent.KEYCODE_ENTER) {
                InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(
                        Context.INPUT_METHOD_SERVICE);
                inputMethodManager.hideSoftInputFromWindow(v.getWindowToken(), 0);
                return true;
            }
            return false;
        }
    });

    mUIThreadRealm = Realm.getDefaultInstance();
}
 
Example 8
Source File: RealmManagerBase.java    From exchange-rates-mvvm with Apache License 2.0 5 votes vote down vote up
protected <T> T readFromRealmSync(SyncCallable<T> callable) {
    Realm realm = null;
    try {
        realm = Realm.getDefaultInstance();
        realm.beginTransaction();
        return callable.execute(realm);
    } finally {
        if (realm != null) {
            realm.commitTransaction();
            realm.close();
        }
    }
}
 
Example 9
Source File: RealmManager.java    From sleep-cycle-alarm with GNU General Public License v3.0 5 votes vote down vote up
public static void incrementCount() {
    if(activityCount == 0) {
        if(realm != null && !realm.isClosed()) {
            Log.w(RealmManager.class.getName(), "Unexpected open Realm found.");
            realm.close();
        }
        Log.d(RealmManager.class.getName(),
                "Incrementing Activity Count [0]: opening Realm.");
        realm = Realm.getDefaultInstance();
    }
    activityCount++;
    Log.d(RealmManager.class.getName(), "Increment: Count [" + activityCount + "]");
}
 
Example 10
Source File: FragmentNotificationViewModel.java    From iGap-Android with GNU Affero General Public License v3.0 5 votes vote down vote up
public FragmentNotificationViewModel(FragmentNotificationBinding fragmentNotificationBinding, long roomId) {
    this.fragmentNotificationBinding = fragmentNotificationBinding;
    this.roomId = roomId;

    realm = Realm.getDefaultInstance();
    roomType = RealmRoom.detectType(roomId);
    getInfo();

    startNotificationState();
    startVibrate();
    startSound();
    startLedColor();
}
 
Example 11
Source File: RealmRegisteredInfo.java    From iGap-Android with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * check info existence in realm if exist and cacheId is equal, will be returned;
 * otherwise send 'RequestUserInfo' to server and after get response will be called
 * 'OnInfo' for return 'RealmRegisteredInfo'
 *
 * @param onRegistrationInfo RealmRegisteredInfo will be returned with this interface
 */
public static void getRegistrationInfo(long userId, @Nullable String cacheId, Realm realm, final OnInfo onRegistrationInfo) {

    RealmRegisteredInfo realmRegisteredInfo = RealmRegisteredInfo.getRegistrationInfo(realm, userId);
    if (realmRegisteredInfo != null && (cacheId == null || realmRegisteredInfo.getCacheId().equals(cacheId))) {
        onRegistrationInfo.onInfo(realmRegisteredInfo.getId());
    } else {
        RequestUserInfo.infoHashMap.put(userId, onRegistrationInfo);
        G.onRegistrationInfo = new OnRegistrationInfo() {
            @Override
            public void onInfo(ProtoGlobal.RegisteredUser registeredInfo) {
                Realm realm1 = Realm.getDefaultInstance();
                OnInfo InfoListener = RequestUserInfo.infoHashMap.get(registeredInfo.getId());
                if (InfoListener != null) {
                    RealmRegisteredInfo realmRegisteredInfo = RealmRegisteredInfo.getRegistrationInfo(realm1, registeredInfo.getId());
                    if (realmRegisteredInfo != null) {
                        InfoListener.onInfo(realmRegisteredInfo.getId());
                    }
                }
                RequestUserInfo.infoHashMap.remove(registeredInfo.getId());
                realm1.close();
            }
        };
        new RequestUserInfo().userInfo(userId, RequestUserInfo.InfoType.JUST_INFO.toString());
    }

}
 
Example 12
Source File: ListsFragment.java    From citrus with Apache License 2.0 4 votes vote down vote up
@Override
public void onAttach(Context context) {
    super.onAttach(context);

    mUIThreadRealm = Realm.getDefaultInstance();
}
 
Example 13
Source File: AppModule.java    From MovieGuide with MIT License 4 votes vote down vote up
@Provides
@Singleton
public Realm provideRealm() {
    return Realm.getDefaultInstance();
}
 
Example 14
Source File: FragmentRegisterViewModel.java    From iGap-Android with GNU Affero General Public License v3.0 4 votes vote down vote up
private void getUserInfo() {

        G.onUserInfoResponse = new OnUserInfoResponse() {
            @Override
            public void onUserInfo(final ProtoGlobal.RegisteredUser user, String identity) {

                Realm realm = Realm.getDefaultInstance();
                realm.executeTransaction(new Realm.Transaction() {
                    @Override
                    public void execute(Realm realm) {
                        G.displayName = user.getDisplayName();

                        RealmUserInfo.putOrUpdate(realm, user);

                        G.handler.post(new Runnable() {
                            @Override
                            public void run() {
                                G.onUserInfoResponse = null;
                                G.currentActivity.finish();
                                Intent intent = new Intent(context, ActivityMain.class);
                                intent.putExtra(FragmentRegistrationNickname.ARG_USER_ID, userId);
                                intent.addFlags(FLAG_ACTIVITY_NEW_TASK);
                                G.context.startActivity(intent);
                            }
                        });
                    }
                });
                realm.close();
            }

            @Override
            public void onUserInfoTimeOut() {
                requestUserInfo();
            }

            @Override
            public void onUserInfoError(int majorCode, int minorCode) {

            }
        };
    }
 
Example 15
Source File: PermissionHelper.java    From my-first-realm-app with Apache License 2.0 4 votes vote down vote up
/**
 * Configure the permissions on the Realm and each model class.
 * This will only succeed the first time that this code is executed. Subsequent attempts
 * will silently fail due to `canSetPermissions` having already been removed.
 *
 * @param postInitialization block to run after the Role has been added or found, usually a
 *                           navigation to the next screen.
 */
public static void initializePermissions(Runnable postInitialization) {
    Realm realm = Realm.getDefaultInstance();
    RealmPermissions realmPermission = realm.where(RealmPermissions.class).findFirst();
    if (realmPermission == null || realmPermission.getPermissions().first().canModifySchema()) {
        // Permission schema is not yet locked
        // Temporary workaround: register an async query to wait until the permission system is synchronized before applying changes.
        RealmResults<RealmPermissions> realmPermissions = realm.where(RealmPermissions.class).findAllAsync();
        realmPermissions.addChangeListener((permissions, changeSet) -> {
            if (changeSet.isCompleteResult()) {
                realmPermissions.removeAllChangeListeners();
                // setup and lock the schema
                realm.executeTransactionAsync(bgRealm -> {
                    // Remove update permissions from the __Role table to prevent a malicious user
                    // from adding themselves to another user's private role.
                    Permission rolePermission = bgRealm.where(ClassPermissions.class).equalTo("name", "__Role").findFirst().getPermissions().first();
                    rolePermission.setCanUpdate(false);
                    rolePermission.setCanCreate(false);

                    // Lower "everyone" Role on Message & PrivateChatRoom and PublicChatRoom to restrict permission modifications
                    Permission messagePermission = bgRealm.where(ClassPermissions.class).equalTo("name", "Message").findFirst().getPermissions().first();
                    Permission publicChatPermission = bgRealm.where(ClassPermissions.class).equalTo("name", "PrivateChatRoom").findFirst().getPermissions().first();
                    Permission privateChatPermission = bgRealm.where(ClassPermissions.class).equalTo("name", "PublicChatRoom").findFirst().getPermissions().first();
                    messagePermission.setCanQuery(false); // Message are not queryable since they're accessed via RealmList (from PublicChatRoom or PrivateChatRoom)
                    messagePermission.setCanSetPermissions(false);
                    publicChatPermission.setCanSetPermissions(false);
                    privateChatPermission.setCanSetPermissions(false);

                    // Lock the permission and schema
                    RealmPermissions permission = bgRealm.where(RealmPermissions.class).equalTo("id", 0).findFirst();
                    Permission everyonePermission = permission.getPermissions().first();
                    everyonePermission.setCanModifySchema(false);
                    everyonePermission.setCanSetPermissions(false);
                }, () -> {
                    realm.close();
                    postInitialization.run();
                });
            }
        });
    } else {
        realm.close();
        postInitialization.run();
    }
}
 
Example 16
Source File: RealmRoomMessageContact.java    From iGap-Android with GNU Affero General Public License v3.0 4 votes vote down vote up
public void addPhone(String phone) {
    Realm realm = Realm.getDefaultInstance();
    phones.add(RealmString.string(realm, phone));
    realm.close();
}
 
Example 17
Source File: SearchFragment.java    From iGap-Android with GNU Affero General Public License v3.0 4 votes vote down vote up
private void fillHashtag(String text) {

        Realm realm = Realm.getDefaultInstance();

        if (!text.startsWith("#")) {
            text = "#" + text;
        }
        final RealmResults<RealmRoomMessage> results = realm.where(RealmRoomMessage.class).equalTo(RealmRoomMessageFields.HAS_MESSAGE_LINK, true).contains(RealmRoomMessageFields.MESSAGE, text, Case.INSENSITIVE).equalTo(RealmRoomMessageFields.EDITED, false).isNotEmpty(RealmRoomMessageFields.MESSAGE).findAll();

        if (results != null && results.size() > 0) {

            addHeader(G.fragmentActivity.getResources().getString(R.string.hashtag));
            for (RealmRoomMessage roomMessage : results) {


                StructSearch item = new StructSearch();

                item.time = roomMessage.getUpdateTime();
                item.comment = roomMessage.getMessage();
                item.id = roomMessage.getRoomId();
                item.type = SearchType.message;
                item.messageId = roomMessage.getMessageId();

                RealmRoom realmRoom = realm.where(RealmRoom.class).equalTo(RealmRoomFields.ID, roomMessage.getRoomId()).findFirst();

                if (realmRoom != null) { // room exist
                    item.name = realmRoom.getTitle();
                    item.initials = realmRoom.getInitials();
                    item.color = realmRoom.getColor();
                    item.roomType = realmRoom.getType();
                    item.avatar = realmRoom.getAvatar();
                    if (realmRoom.getType() == ProtoGlobal.Room.Type.CHAT && realmRoom.getChatRoom() != null) {
                        item.idDetectAvatar = realmRoom.getChatRoom().getPeerId();
                    } else {
                        item.idDetectAvatar = realmRoom.getId();
                    }
                    list.add(item);
                }
            }
        }

        realm.close();

    }
 
Example 18
Source File: ProjectsActivity.java    From my-first-realm-app with Apache License 2.0 4 votes vote down vote up
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_items);

    setSupportActionBar(findViewById(R.id.toolbar));

    findViewById(R.id.fab).setOnClickListener(view -> {
        View dialogView = LayoutInflater.from(this).inflate(R.layout.dialog_task, null);
        ((EditText) dialogView.findViewById(R.id.task)).setHint(R.string.project_description);
        EditText taskText = dialogView.findViewById(R.id.task);
        new AlertDialog.Builder(ProjectsActivity.this)
                .setTitle("Add a new project")
                .setView(dialogView)
                .setPositiveButton("Add", (dialog, which) -> realm.executeTransactionAsync(realm -> {
                    String userId = SyncUser.current().getIdentity();
                    String name = taskText.getText().toString();

                    Project project = new Project();
                    project.setId(UUID.randomUUID().toString());
                    project.setOwner(userId);
                    project.setName(name);
                    project.setTimestamp(new Date());

                    realm.insert(project);
                }, error -> RealmLog.error(error) ))
                .setNegativeButton("Cancel", null)
                .create()
                .show();
    });

    // Create a  subscription that only download the  users projects from the server.
    realm = Realm.getDefaultInstance();
    RealmResults<Project> projects = realm
            .where(Project.class)
            .equalTo("owner", SyncUser.current().getIdentity())
            .sort("timestamp", Sort.DESCENDING)
            .findAllAsync();

    final ProjectsRecyclerAdapter itemsRecyclerAdapter = new ProjectsRecyclerAdapter(this, projects);
    RecyclerView recyclerView = findViewById(R.id.recycler_view);
    recyclerView.setLayoutManager(new LinearLayoutManager(this));
    recyclerView.setAdapter(itemsRecyclerAdapter);
}
 
Example 19
Source File: ProjectsActivity.java    From my-first-realm-app with Apache License 2.0 4 votes vote down vote up
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_items);

    setSupportActionBar(findViewById(R.id.toolbar));

    final String userId = SyncUser.current().getIdentity();

    findViewById(R.id.fab).setOnClickListener(view -> {
        View dialogView = LayoutInflater.from(this).inflate(R.layout.dialog_task, null);
        EditText taskText = dialogView.findViewById(R.id.task);
        new AlertDialog.Builder(ProjectsActivity.this)
                .setTitle("Add a new project")
                .setView(dialogView)
                .setPositiveButton("Add", (dialog, which) -> realm.executeTransactionAsync(realm -> {

                    String name = taskText.getText().toString();
                    Project project = realm.createObject(Project.class, UUID.randomUUID().toString());
                    project.setName(name);
                    project.setTimestamp(new Date());

                    // Create a restrictive permission to limit read/write access to the current user only
                    Role role = realm.where(PermissionUser.class)
                            .equalTo("id", userId)
                            .findFirst()
                            .getPrivateRole();
                    Permission permission = new Permission.Builder(role).allPrivileges().build();
                    project.getPermissions().add(permission);
                }))
                .setNegativeButton("Cancel", null)
                .create()
                .show();
    });

    // perform a partial query to obtain
    // only projects belonging to our  SyncUser.
    // the permission system will filter out and return only our projects, no
    // need to filter by the project owner like we did in Tutorial#2 (PartialSync)
    realm = Realm.getDefaultInstance();
    RealmResults<Project> projects = realm
            .where(Project.class)
            .sort("timestamp", Sort.DESCENDING)
            .findAllAsync();

    final ProjectsRecyclerAdapter itemsRecyclerAdapter = new ProjectsRecyclerAdapter(this, projects);
    RecyclerView recyclerView = findViewById(R.id.recycler_view);
    recyclerView.setLayoutManager(new LinearLayoutManager(this));
    recyclerView.setAdapter(itemsRecyclerAdapter);
}
 
Example 20
Source File: ApiStorage.java    From ApiClient with Apache License 2.0 4 votes vote down vote up
public ApiStorage(){
    this.mRealm = Realm.getDefaultInstance();
}