从另一个活动更新存储在一个活动中的对象 [英] Updating an object stored in one Activity from another activity

查看:69
本文介绍了从另一个活动更新存储在一个活动中的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要在第一个活动中创建一个名为"AppEngine"的对象.这个AppEngine对象存储事件的arrayList和事件,并以其中的2个事件开始.

I am creating an object called "AppEngine" inside my first activity. This AppEngine object stores and arrayList of Events, and begins with 2 events inside it.

在第一个活动中,单击一个按钮,将我带到第二个活动,在第二个活动中,我通过使用将事件对象添加到arrayList.

From the first Activity I click a button which takes me to a second Activity in which I add an event object to the arrayList by using.

appEngine.getList.add(new Event)

在活动2中,如果我要呼叫appEngine.getList.size(),则大小正确返回为3,我可以看到额外的事件.

When inside Activity 2, If I am to call appEngine.getList.size() the size is correctly returned as 3 and I can see the extra event.

当我切换回活动2时,我正在调用appEngine.getList.size(),但是它仅返回2,并且没有额外的事件.我该如何更新appEngine对象?

When I switch back to Activity 2, I am calling appEngine.getList.size()however it only returns 2, and the extra event is not in there. How can i get the appEngine object to update?

推荐答案

您可以使用 Singleton 设计模式.

您可以从带有事件列表字段的 AppEnginRepository 创建一个对象,然后在您的应用中获取它,并且每次您想要更改

You create one object from AppEnginRepository with eventList field and in your app you just get it and each time you want, you change it.

public class AppEnginRepository {

    private List<Event> eventList;

    private static final AppEnginRepository ourInstance = new AppEnginRepository();

    public static AppEnginRepository getInstance() {
        return ourInstance;
    }

    private AppEnginRepository() {
        eventList = new ArrayList<>();
    }

    public List<Event> getEventList() {
        return eventList;
    }

    public void setEventList(List<Event> eventList) {
        this.eventList = eventList;
    }


}

在您的活动中

AppEnginRepository enginRepository=AppEnginRepository.getInstance();
List<Event> eventList=enginRepository.getEventList();
eventList.add(new Event());
int eventListSize=eventList.size();

这篇关于从另一个活动更新存储在一个活动中的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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