观察者不更新数据
Observer do not update data
我为模型的数据实现了一个观察器;
我有 2 activity,它们共享该数据。在我的第一个 activity 中,我将模型设置为:
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();
}
}
在第二个 activity 中,我将观察者设置为:
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 一起使用,但结果相同。
我哪里做错了?
非常感谢。
您需要通过调用以下方法将第二个视图 Activity 添加为 ConnectionModel
的 Observer
:
ConnectionModel.getInstance().addObserver(this);
在第二个视图中 activity。
我为模型的数据实现了一个观察器; 我有 2 activity,它们共享该数据。在我的第一个 activity 中,我将模型设置为:
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();
}
}
在第二个 activity 中,我将观察者设置为:
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 一起使用,但结果相同。
我哪里做错了?
非常感谢。
您需要通过调用以下方法将第二个视图 Activity 添加为 ConnectionModel
的 Observer
:
ConnectionModel.getInstance().addObserver(this);
在第二个视图中 activity。