简体   繁体   English

Android Parcelable和通过引用传递的对象

[英]Android Parcelable and object passing by reference

I have numerous objects, some of which would have different ArrayList properties (of custom objects). 我有很多对象,其中一些对象具有不同的ArrayList属性(自定义对象)。 The same object could occurr in any of the above ArrrayList. 任何上述ArrrayList中都可能出现相同的对象。

I would like to have those objects being passed by reference so that when I edit one of them, the changes are reflected across all ArrayLists/objects. 我希望通过引用传递这些对象,以便在编辑其中一个对象时,更改将反映在所有ArrayLists /对象中。

I need to pass those objects or ArrayLists as Parcelable across different Activities. 我需要将这些对象或ArrayLists作为Parcelable传递到不同的Activity。 I think Parcelable interface is causing passing by reference not working (which kind of makes sense considering you need to implement new constructor, so supposedly the new object is created/cloned every time Parcel is being created and passed?). 我认为Parcelable接口导致通过引用传递不起作用(考虑到你需要实现新的构造函数,哪种有意义,所以据说每次创建和传递Parcel时都会创建/克隆新对象?)。

I was wondering what would be the best approach to handle this situation, ie. 我想知道处理这种情况的最佳方法是什么,即。 how can I achieve or simulate the behaviour of the objects being passed by reference. 如何实现或模拟通过引用传递的对象的行为。 I dont really want to use any of the persistent storage tehniques if it can be avoided. 如果可以避免的话,我真的不想使用任何持久性存储技术。

I know this is an old question, but since I'me here :) 我知道这是一个老问题,但是因为我在这里:)

Anyway what I do is pass the id of the item I want and then use Application to hold my data. 无论如何我做的是传递我想要的项目的ID,然后使用应用程序来保存我的数据。

For example let's say I have a class named Order, each order has many Line(s) something like this 例如,假设我有一个名为Order的类,每个订单都有很多这样的Line

class Order {
    UUID _id;
    List<Line> _lines = new ArrayList<>();
}

class Line {
    UUID _id;
    Product _product ;
    BigDecimal _price;
    int _quantity;
}

etc. 等等

So I have an implementation of Application where I store all my (in memory) orders like this: 所以我有一个Application的实现,我存储了所有我的(内存)命令,如下所示:

public class App extends Application {
    public static final List<Order> Orders = new Order();

    public static final Order GetOrder(UUID id) {
        for (Order o : Orders) {
            If(o.get_id().Equals(id))
            return o;
        }
        return null;
    }
}

Then if I wish to pass a specific order I do something like this: 然后,如果我希望通过特定的订单,我会做这样的事情:

Intent i = new Intent(this, OrderEdit.class);
i.putExtra(OrderEdit.ID, my_order.get_id().ToString());
startActivity(i);

and on the other side : 在另一边:

UUID id = UUID.fromString(getArguments().getExtra(ID));
App.GetOrder(id); 

that way you always have a reference passed. 这样你总是有一个参考传递。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM