可观察的Java对象不会更新 [英] Observable java object doesnt update
问题描述
这是我的ActivityA:
this is my ActivityA:
public class ActivityA extends AppCompatActivity implement Observer
{
private Mouse _mouse;
@Override
protected void onCreate(Bundle savedInstanceState)
{
...
_mouse = new Mouse();
_mouse.posX = 30;
_mouse.addObserver(this);
}
@Override
public void onClick(View v)
{
Intent intent = new Intent(ActivityA.this, ActivityB.class);
intent.putExtra("Mouse", Parcels.wrap(mouse));
startActivity(intent)
}
@Override
public void update(Observable o, Object arg)
{
// Never get called.
Log.e("TAG", "We're updating the object");
}
}
这是我的ActivityB:
And this is my ActivityB:
public class ActivityB extends AppCompatActivity
{
private Mouse _mouse;
@Override
protected void onCreate(Bundle savedInstanceState)
{
...
_mouse = Parcels.unwrap(getIntent().getParcelableExtra("Mouse"));
Log.v("AB", "X: "_mouse.posX); // This is 30
}
@Override
public void onClick(View v)
{
_mouse.posX = 100;
_mouse.NotifyObservers();
}
}
最后,我的模型如下:
public class Mouse extends Observable
{
public int posX;
public void NotifyObservers()
{
setChanged();
notifyObservers();
}
}
我无法使用它,因为从未调用过ActivityA中的更新".也许我忘记了什么?在不使用活动结果代码的情况下从其他活动更新对象时,有没有更好的通知方式?
I can't get it working because "update" in ActivityA is never called. Maybe I forgot something? Is there any better way of notify when a object is updated from other activity without using activity result code?
推荐答案
-
首先需要注册您的观察者,然后通过在
_mouse = new Mouse();
使用
Parcels wrap and unwrap
使您成为Mouse
模型parcelable
的第二件事.甚至您使用过serializable
都行不通.Second thing you've made you
Mouse
modelparcelable
usingParcels wrap and unwrap
. and even you have you have usedserializable
it doesn't work.因为您已经在
Mouse
类扩展的Obervable
中注册了侦听器,而该类具有观察者列表,则无法将其包裹或进行序列化.Because you have registered your listener in
Obervable
extended byMouse
class which has list of obeservers is not parcelable or serializable.因此,每当将模型传递给
ActivityB
时,都会删除ActivityA
的旧侦听器.So whenever you're passing your model to
ActivityB
, old listener ofActivityA
is removed.要检查我的答案,请先执行我指示的步骤,然后从
ActivityA
本身调用_mouse.NotifyObservers();
.To check my answer do first step which I have indicated and call
_mouse.NotifyObservers();
fromActivityA
itself.您将在
update
上获得回调.这篇关于可观察的Java对象不会更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!