单击时切换按钮

时间:2017-01-22 22:23:23

标签: realm realm-java

我有一个"订阅"我的一个视图中的按钮,允许用户订阅另一个用户的更新。按钮在" subscribe"之间切换。和"订阅"。

以下是负责该观点的活动:

public class ProfileActivity extends BaseActivity {
    private Realm realm;

    private User user;

    private Subscribe subscribe = null;

    private Button subscribeButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        realm = Realm.getDefaultInstance();

        // Get the user's information
        user = (User) getIntent().getSerializableExtra("user");

        subscribeButton = (Button) findViewById(R.id.subscribeButton);

        // Check if already subscribed to this user
        subscribe = realm.where(Subscribe.class)
                .equalTo("userId", user.getId())
                .findFirst();
    }

    // The onClick method for the subscribe button
    public void subscribeToUser(View view) {
        Boolean isSubscribed = subscribe != null;

        realm.beginTransaction();

        if (isSubscribed) {
            // Unsubscribe

            if (subscribe != null) {
                subscribe.deleteFromRealm();
                subscribe = null;
            }
        } else {
            // Subscribe

            User newUser = realm.copyToRealmOrUpdate(user);

            subscribe = realm.createObject(Subscribe.class, user.getId());
            subscribe.setUser(newUser);
        }

        realm.commitTransaction();
    }
}

我只是想知道这是否是正确的方法,或者我的代码中是否应该更改某些内容,特别是subscribeToUser()方法

感谢。

0 个答案:

没有答案