简体   繁体   English

领域正在使用旧对象,而不是对其进行更新

[英]Realm is using old object, not updating it

I am using Realm for saving user input from EditText in Fragment 1 , and showing that input inside TextView of Fragment 2.When user clicks button inside first Fragment , I need to show that text inside second Fragment. 我正在使用Realm从Fragment 1中的EditText保存用户输入,并在Fragment 2的TextView中显示该输入。当用户单击第一个Fragment中的按钮时,我需要在第二个Fragment中显示该文本。

Everything seems fine, but every time I lunch my app, query is excetuded before saving object and old input is shown inside TextView. 一切似乎都很好,但是每当我午餐我的应用程序时,在保存对象之前都会取消查询,并且旧输入会显示在TextView中。

  • When I enter some input, old text has been saved already and shown inside TextView 当我输入一些内容时,旧文本已经保存并显示在TextView中

Here is method for saving input, and OnClick Method inside Fragment 1 : 这是保存输入的方法,以及片段1内的OnClick方法:

public void setEmail() {
   Realm realm = getRealm();
   realm.beginTransaction();
   final Email emailInput = new Email();
   emailInput.setUsername(editEmail.getText().toString());

   realm.copyToRealmOrUpdate(emailInput);
   realm.commitTransaction();


}


@OnClick(R.id.btn_forgot)
public void onButtonClick() {

   setEmail();

}

. Here is method for query and setting text inside Fragment 2 : 这是在片段2中查询和设置文本的方法:

public void getEmail() {
   Realm realm = getRealm();
   RealmQuery<Email> queryUser = realm.where(Email.class);
   Email resultEmail = queryUser.findFirst();

   resendEmailTxt = (AutoResizeTextView) getView().findViewById(R.id.resend_user_email);
   if (resendEmailTxt != null) {
       this.resendEmailTxt.setText(resultEmail.getUsername());
   }


}
@Override
public void onStart() {
   super.onStart();
   getEmail();


}

Model class: 型号类别:

public class Email extends RealmObject {

@PrimaryKey
public int id = 0;
private String username;

//Getters and setters here

 }

Second Fragment queries data when it starts, that is before onClick event from first Fragment can happen (because both fragments get created roughly at the same time). 第二个片段开始查询数据时,即在第一个片段的onClick事件发生之前(因为两个片段大致同时创建)。

You need to inform second fragment that the data has been changed in the first one. 您需要告知第二个片段第一个片段中的数据已更改。 There are many ways of accomplishing that, eg.: 有很多方法可以实现这一目标,例如:

  • interface 接口
  • event bus (Otto, EventBus) 事件总线(Otto,EventBus)
  • reactive programming 反应式编程

There is probably a lot more but one of these will be enough ;) 可能还有很多,但是其中之一就足够了;)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM