Observable java object doesnt update

我的梦境 提交于 2019-12-25 04:17:06

问题


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?


回答1:


  • 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.



来源:https://stackoverflow.com/questions/40627703/observable-java-object-doesnt-update

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!