简体   繁体   中英

android Observer method update not work

I use observer pattern

recently , In my main class,

MainActivity.class

static private AutoObservable observable;   //global variable 
private Agency agency = null; //global variable

@Override
protected void onStart() {
   super.onStart();
   observable = agency;
   observable.addObserver(new Observerclass(agency.RoomName()));
}

AutoObservable.class

public class AutoObservable extends Observable {
@Override
public void notifyObservers(Object data) {
    super.setChanged();
    super.notifyObservers(data);
    super.clearChanged();
}
}

Observerclass.class

public class Observerclass implements Observer {
   private final String roomName;
   public Observerclass(String roomName) {
         this.roomName = roomName;
   }

   @Override
   public void update(Observable observable, Object o) {
      . . .   // not work ..
   } 

perhaps,, permission problem?.. please advice for me.

You do not have to override notifyObservers() , so, remove this code block from AutoObservable

@Override
public void notifyObservers(Object data) {
    super.setChanged();
    super.notifyObservers(data);
    super.clearChanged();
}

Instead, do something like in AutoObservable.java

public void onSomeEvent() {
    setChanged();
    notifyObservers(data);
}

And, from MainActivity call Observer instance like

observable.onSomeEvent();

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