Android Parcelable and objects are passed by reference
I have many objects, some of which have different ArrayList properties (custom objects). The same object may appear in any of these ArrrayList.
I
want to pass these objects by reference so that when I edit one of them, the change is reflected in all ArrayLists/objects.
I need to pass these objects or ArrayLists as parcelable to different activities. I think the Parcelable interface is causing passing by reference not to work (which makes sense considering you need to implement a new constructor, so let’s say a new object is created/cloned every time a parcel is created and passed?). )。
I would like to know what is the best way to deal with this situation, ie. How can I implement or simulate the behavior of an object passed by reference. I don’t really want to use any persistent storage technology if it can be avoided.
Solution
I
know it’s an old question, but since I’m here 🙂
Anyway, what I did was pass the ID of the item I wanted and then use Application to save my data.
For example, let’s say I have a class called Order and there are many such Line(s) for each order
class Order {
UUID _id;
List<Line> _lines = new ArrayList<>();
}
class Line {
UUID _id;
Product _product ;
BigDecimal _price;
int _quantity;
}
And so on
So I have an implementation of an application where I store all my (in memory) orders as follows:
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 want to go through 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);
On the other side:
UUID id = UUID.fromString(getArguments().getExtra(ID));
App.GetOrder(id);
This way you can always pass a reference.