简体   繁体   中英

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.

Everything seems fine, but every time I lunch my app, query is excetuded before saving object and old input is shown inside TextView.

  • When I enter some input, old text has been saved already and shown inside TextView

Here is method for saving input, and OnClick Method inside Fragment 1 :

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 :

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).

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)
  • reactive programming

There is probably a lot more but one of these will be enough ;)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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