Reputation: 247
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");
}
}
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();
}
}
Finally my model looks like this:
public class Mouse extends Observable
{
public int posX;
public void NotifyObservers()
{
setChanged();
notifyObservers();
}
}
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?
Upvotes: 0
Views: 479
Reputation: 1249
First thing you need to register your observer to getting update called by doing _mouse.addObserver(this);
just after _mouse = new Mouse();
Second thing you've made you Mouse
model parcelable
using Parcels wrap and unwrap
. and even you have you have used serializable
it doesn't work.
Because you have registered your listener in Obervable
extended by Mouse
class which has list of obeservers is not parcelable or serializable.
So whenever you're passing your model to ActivityB
, old listener of ActivityA
is removed.
To check my answer do first step which I have indicated and call _mouse.NotifyObservers();
from ActivityA
itself.
you'll get callback on update
.
Upvotes: 1