观察者不更新数据

时间:2019-02-21 10:39:28

标签: java android observers

我为模型的数据实现了一个观察者; 我有2个活动,共享这些数据。在我的第一个活动中,我将模型设置为:

public void refreshValue (String id, Data data){
ConnectionModel.getInstance().updateConnection(data);

在模型中,updateConnection类似于:

public class ConnectionModel extends Observable{
//...
  synchronized Connection getConnection() {
    return connection;
  }
  void updateConnection(Data data){
      synchronized (this) {
          connection.setData(data);
      }
      setChanged();
      notifyObservers();
  }
}

在第二个活动中,我将观察者设置为:

public class secondView extends AppCompatActivity implements Observer {
public void observe(Observable o) {
    o.addObserver(this);
}
//...
public void refreshView(){
    Connection connection = ConnectionModel.getInstance().getConnection();       
    heartRate.setText(connection.toString());
}


@Override
public void update(Observable o, Object arg) {
    refreshView();
    Log.d("update", "data is change");
}

我还尝试将LiveData与ViewModel一起使用,但结果相同。

我在哪里做错了?

非常感谢。

1 个答案:

答案 0 :(得分:0)

您需要通过调用以下命令将secondView活动添加为Observer的{​​{1}}:

ConnectionModel

secondView活动内部。

相关问题