android Observer方法更新不起作用

时间:2016-07-20 07:42:07

标签: java android

我使用观察者模式

最近,在我的主要课程中,

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 ..
   } 
或许,许可问题?.. 请给我建议。

1 个答案:

答案 0 :(得分:0)

您不必覆盖notifyObservers(),因此,请从AutoObservable

中删除此代码块
@Override
public void notifyObservers(Object data) {
    super.setChanged();
    super.notifyObservers(data);
    super.clearChanged();
}

相反,请执行AutoObservable.java

之类的操作
public void onSomeEvent() {
    setChanged();
    notifyObservers(data);
}

并且,从MainActivity调用Observer实例

observable.onSomeEvent();