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

The following examples show how to use io.realm.Realm#beginTransaction() . 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: 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 2
Source File: GroupRealm.java    From talk-android with MIT License 6 votes vote down vote up
public List<Group> getAllGroupsWithCurrentThread() {
    List<Group> results = new ArrayList<>();
    Realm realm = RealmProvider.getInstance();
    try {
        realm.beginTransaction();
        RealmResults<Group> groups = realm.where(Group.class)
                .equalTo(Group.TEAM_ID, BizLogic.getTeamId())
                .findAll();
        for (Group group : groups) {
            Group result = new Group();
            copy(result, group);
            results.add(result);
        }
        realm.commitTransaction();
    } catch (Exception e) {
        e.printStackTrace();
        realm.cancelTransaction();
    } finally {
        realm.close();
    }
    return results;
}
 
Example 3
Source File: ApiImpl.java    From Theogony with MIT License 6 votes vote down vote up
@Override
public boolean writeToRealmDataBase(DragonData dragonData) {
    if (dragonData == null) return false;

    Realm realm = RealmProvider.getInstance().getRealm();
    try {
        realm.beginTransaction();
        realm.deleteAll();
        realm.copyToRealm(dragonData);
        realm.commitTransaction();
        return true;
    } catch (Exception e) {
        LogHelper.LOGW("数据写入失败:" + e);
    } finally {
        realm.close();
    }
    return false;
}
 
Example 4
Source File: MessageRealm.java    From talk-android with MIT License 6 votes vote down vote up
public List<Message> getUnSendMessageWithCurrentThread(final String foreignId) {
    final List<Message> messages = new ArrayList<>();
    Realm realm = RealmProvider.getInstance();
    try {
        realm.beginTransaction();
        RealmResults<Message> realmResults = realm.where(Message.class)
                .equalTo(Message.TEAM_ID, BizLogic.getTeamId())
                .equalTo(Message.FOREIGN_ID, foreignId)
                .notEqualTo(Message.STATUS, 0)
                .findAll();
        realmResults.sort(Message.CREATE_AT_TIME, Sort.ASCENDING);
        for (Message realmResult : realmResults) {
            final Message message = new Message();
            copy(message, realmResult);
            messages.add(message);
        }
        realm.commitTransaction();
    } catch (Exception e) {
        e.printStackTrace();
        realm.cancelTransaction();
    } finally {
        realm.close();
    }
    return messages;
}
 
Example 5
Source File: NotificationRealm.java    From talk-android with MIT License 6 votes vote down vote up
public void batchAddWithCurrentThread(final List<Notification> notifications) {
    List<Notification> realmNotifications = new ArrayList<>(notifications.size());
    Realm realm = RealmProvider.getInstance();
    try {
        for (Notification realmNotification : notifications) {
            Notification notification = new Notification();
            copy(notification, realmNotification);
            realmNotifications.add(notification);
        }
        realm.beginTransaction();
        realm.copyToRealmOrUpdate(realmNotifications);
        realm.commitTransaction();
    } catch (Exception e) {
        e.printStackTrace();
        realm.cancelTransaction();
    } finally {
        realm.close();
    }
}
 
Example 6
Source File: FavoritesManager.java    From Theogony with MIT License 6 votes vote down vote up
public void add(final Champion champion) {
    if (champion == null) return;
    Realm realm = RealmProvider.getInstance().getRealm();
    try {
        realm.beginTransaction();

        int primaryKey = 0;
        Number number = realm.where(Favorites.class).max("id");
        if (number != null) {
            primaryKey = number.intValue() + 1;
        } else {
            primaryKey = 1;
        }
        Favorites favorites = realm.createObject(Favorites.class, primaryKey);
        favorites.setChampionId(champion.getId());
        favorites.setChampion(champion);

        realm.commitTransaction();
    } finally {
        realm.close();
    }
}
 
Example 7
Source File: XMPPSession.java    From mangosta-android with Apache License 2.0 6 votes vote down vote up
private void manageMessageAlreadyExists(Message message, Date delayDate, String messageId) {
    Realm realm = RealmManager.getInstance().getRealm();
    realm.beginTransaction();

    ChatMessage chatMessage = realm.where(ChatMessage.class).equalTo("messageId", messageId).findFirst();
    chatMessage.setStatus(ChatMessage.STATUS_SENT);

    if (isBoBMessage(message)) {
        BoBExtension bobExtension = BoBExtension.from(message);
        chatMessage.setContent(Base64.decodeToString(bobExtension.getBoBHash().getHash()));
    } else {
        chatMessage.setContent(message.getBody());
    }

    if (delayDate != null) {
        chatMessage.setDate(delayDate);
    }

    realm.copyToRealmOrUpdate(chatMessage);
    realm.commitTransaction();
    realm.close();
}
 
Example 8
Source File: RealmBufferResolver.java    From TimberLorry with Apache License 2.0 6 votes vote down vote up
@Override
public void save(Serializer serializer, Payload payload) {
    Record record = new Record(payload.getClass(), serializer.serialize(payload));
    Realm realm = null;
    try {
        realm = Realm.getInstance(realmConfig);
        realm.beginTransaction();
        RecordObject obj = realm.createObject(RecordObject.class);
        obj.setClassName(record.getClazz().getCanonicalName());
        obj.setBody(record.getBody());
        realm.commitTransaction();
    } finally {
        if (realm != null)
            realm.close();
    }
}
 
Example 9
Source File: RoomRealm.java    From talk-android with MIT License 6 votes vote down vote up
public void addOrUpdateWithCurrentThread(final Room room) {
    if (room == null) return;
    Realm realm = RealmProvider.getInstance();
    try {
        realm.beginTransaction();
        copy(room, room);
        if (room.getIsGeneral()) {
            room.setTopic(MainApp.CONTEXT.getString(R.string.general));
        }
        realm.copyToRealmOrUpdate(room);
        realm.commitTransaction();
    } catch (Exception e) {
        e.printStackTrace();
        realm.cancelTransaction();
    } finally {
        realm.close();
    }
}
 
Example 10
Source File: BloodGlucoseInputFragment.java    From OpenLibre with GNU General Public License v3.0 5 votes vote down vote up
public void saveBloodGlucoseLevel(long date, float bloodGlucoseLevel) {
    Realm realmUserData = Realm.getInstance(realmConfigUserData);
    realmUserData.beginTransaction();
    realmUserData.copyToRealmOrUpdate(new BloodGlucoseData(date, bloodGlucoseLevel));
    realmUserData.commitTransaction();
    realmUserData.close();
}
 
Example 11
Source File: RealmManager.java    From mangosta-android with Apache License 2.0 5 votes vote down vote up
public void saveBlogPost(BlogPost blogPost) {
    Realm realm = getRealm();

    realm.beginTransaction();
    realm.copyToRealmOrUpdate(blogPost);
    realm.commitTransaction();

    realm.close();
}
 
Example 12
Source File: DatabaseRealm.java    From openwebnet-android with MIT License 5 votes vote down vote up
public <T extends RealmObject> Iterable<T> addAll(Iterable<T> models) {
    Realm realm = getRealmInstance();
    realm.beginTransaction();
    realm.copyToRealm(models);
    realm.commitTransaction();
    return models;
}
 
Example 13
Source File: RoomManager.java    From mangosta-android with Apache License 2.0 5 votes vote down vote up
public void leaveMUCLight(final String jid) {

        MultiUserChatLightManager manager = XMPPSession.getInstance().getMUCLightManager();

        try {
            MultiUserChatLight multiUserChatLight = manager.getMultiUserChatLight(JidCreate.from(jid).asEntityBareJidIfPossible());
            multiUserChatLight.leave();

            Realm realm = RealmManager.getInstance().getRealm();
            realm.beginTransaction();

            Chat chat = realm.where(Chat.class).equalTo("jid", jid).findFirst();
            if (chat != null) {
                chat.setShow(false);
                chat.deleteFromRealm();
            }

            realm.commitTransaction();
            realm.close();
        } catch (Exception e) {
            Context context = MangostaApplication.getInstance();
            Toast.makeText(context, context.getString(R.string.error), Toast.LENGTH_SHORT).show();
            mListener.onError(e.getLocalizedMessage());
        } finally {
            mListener.onRoomLeft();
        }
    }
 
Example 14
Source File: RoomManager.java    From mangosta-android with Apache License 2.0 5 votes vote down vote up
public void leave1to1Chat(String chatJid) {
    Realm realm = RealmManager.getInstance().getRealm();

    Chat chat = realm.where(Chat.class).equalTo("jid", chatJid).findFirst();

    realm.beginTransaction();
    chat.deleteFromRealm();
    realm.commitTransaction();
    realm.close();

    mListener.onRoomLeft();
}
 
Example 15
Source File: NotificationRealm.java    From talk-android with MIT License 5 votes vote down vote up
public void addWithCurrentThread(final Notification notification) {
    Realm realm = RealmProvider.getInstance();
    try {
        realm.beginTransaction();
        Notification realmNotification = realm.createObject(Notification.class);
        copy(realmNotification, notification);
        realm.commitTransaction();
    } catch (Exception e) {
        e.printStackTrace();
        realm.cancelTransaction();
    } finally {
        realm.close();
    }
}
 
Example 16
Source File: MessageRealm.java    From talk-android with MIT License 5 votes vote down vote up
public void addOrUpdateEventWithCurrentThread(Message message, final String... msgId) {
    final Realm realm = RealmProvider.getInstance();
    try {
        realm.beginTransaction();
        copy(message, message);
        realm.copyToRealmOrUpdate(message);
        realm.commitTransaction();
    } catch (Exception e) {
        e.printStackTrace();
        realm.cancelTransaction();
    } finally {
        realm.close();
    }
}
 
Example 17
Source File: DatabaseHelper.java    From redgram-for-reddit with GNU General Public License v3.0 5 votes vote down vote up
public static void setSubreddits(Realm realm, User user, List<SubredditItem> items) {
    realm.beginTransaction();

    if(user.getSubreddits() != null){
        user.getSubreddits().clear();
    }else{
        user.setSubreddits(new RealmList<>());
    }
    for(SubredditItem item : items){
        user.getSubreddits().add(buildSubreddit(item));
    }

    realm.copyToRealmOrUpdate(user);
    realm.commitTransaction();
}
 
Example 18
Source File: RealmManager.java    From mangosta-android with Apache License 2.0 5 votes vote down vote up
public void saveBlogPostComment(BlogPostComment comment) {
    Realm realm = getRealm();

    realm.beginTransaction();
    realm.copyToRealmOrUpdate(comment);
    realm.commitTransaction();

    realm.close();
}
 
Example 19
Source File: xDripIncoming.java    From HAPP with GNU General Public License v3.0 5 votes vote down vote up
public static void New_data(Intent intent, Realm realm){
    Log.d(TAG, "New xDrip Broadcast Received");

    if (intent == null) return;
    Bundle bundle = intent.getExtras();
    if (bundle == null) return;

    final double bgEstimate = bundle.getDouble(Intents.EXTRA_BG_ESTIMATE,0);
    if (bgEstimate == 0) return;

    final Bg bg = new Bg();
    bg.setDirection     (bundle.getString(Intents.EXTRA_BG_SLOPE_NAME));
    bg.setBattery       (bundle.getInt(Intents.EXTRA_SENSOR_BATTERY));
    bg.setBgdelta       (bundle.getDouble(Intents.EXTRA_BG_SLOPE, 0) * 1000 * 60 * 5);
    bg.setDatetime      (new Date(bundle.getLong(Intents.EXTRA_TIMESTAMP, new Date().getTime())));
    bg.setSgv           (Integer.toString((int) bgEstimate, 10));

    realm.beginTransaction();
    realm.copyToRealm(bg);
    realm.commitTransaction();

    Log.d(TAG, "New BG saved, sending out UI Update");

    Intent updateIntent = new Intent(Intents.UI_UPDATE);
    updateIntent.putExtra("UPDATE", "NEW_BG");
    LocalBroadcastManager.getInstance(MainApp.instance()).sendBroadcast(updateIntent);
}
 
Example 20
Source File: RealmExecutor.java    From android-orm-benchmark-updated with Apache License 2.0 4 votes vote down vote up
@Override
public long writeWholeData() throws SQLException
{
    List<User> users = new ArrayList<User>(NUM_USER_INSERTS);
    for (int i = 0; i < NUM_USER_INSERTS; i++) {
        User newUser = new User();
        newUser.setId(i);
        newUser.setmLastName(getRandomString(10));
        newUser.setmFirstName(getRandomString(10));

        users.add(newUser);
    }

    List<Message> messages = new ArrayList<Message>(NUM_MESSAGE_INSERTS);
    for (int i = 0; i < NUM_MESSAGE_INSERTS; i++) {
        Message newMessage = new Message();
        newMessage.setId(i);
        newMessage.setCommandId(i);
        newMessage.setSortedBy(System.nanoTime());
        newMessage.setContent(Util.getRandomString(100));
        newMessage.setClientId(System.currentTimeMillis());
        newMessage
                .setSenderId(Math.round(Math.random() * NUM_USER_INSERTS));
        newMessage
                .setChannelId(Math.round(Math.random() * NUM_USER_INSERTS));
        newMessage.setCreatedAt((int) (System.currentTimeMillis() / 1000L));


        messages.add(newMessage);
    }

    final Realm realm = Realm.getDefaultInstance();
    // Open the Realm for the UI thread.
    realm.beginTransaction();

    long start = System.nanoTime();

    String userLog;
    long messageStart;

    try
    {
        realm.insert(users);

        userLog = "Done, wrote " + NUM_USER_INSERTS + " users" + (System.nanoTime() - start);

        messageStart = System.nanoTime();

        realm.insert(messages);
    }
    finally
    {
        realm.commitTransaction();
        realm.close();
    }

    long totalTime = System.nanoTime() - start;

    Log.d(TAG, userLog);
    Log.d(TAG, "Done, wrote " + NUM_MESSAGE_INSERTS + " messages"  + (System.nanoTime() - messageStart));

    return totalTime;
}