我的一个视图中有一个“订阅”按钮,可让用户订阅另一个用户的更新。该按钮在“订阅”和“订阅”之间切换。
这是负责该视图的活动:
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()
方法中。
谢谢。