可观察的Java对象不会更新 [英] Observable java object doesnt update

查看:83
本文介绍了可观察的Java对象不会更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的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 model parcelable using Parcels wrap and unwrap. and even you have you have used serializable it doesn't work.

    因为您已经在Mouse类扩展的Obervable中注册了侦听器,而该类具有观察者列表,则无法将其包裹或进行序列化.

    Because you have registered your listener in Obervable extended by Mouse class which has list of obeservers is not parcelable or serializable.

    因此,每当将模型传递给ActivityB时,都会删除ActivityA的旧侦听器.

    So whenever you're passing your model to ActivityB, old listener of ActivityA is removed.

    要检查我的答案,请先执行我指示的步骤,然后从ActivityA本身调用_mouse.NotifyObservers();.

    To check my answer do first step which I have indicated and call _mouse.NotifyObservers(); from ActivityA itself.

    您将在update上获得回调.

    这篇关于可观察的Java对象不会更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆