Robert Simoes Robert Simoes - 1 year ago 55
Android Question

Technique for using indexOf when working with Java pass by Value for Parceled Object with dynamic properties?

What kind of technique can be implemented so that the default ArrayList indexOf can be used when all properties of a particular object are dynamically changing (ie. not guaranteed to be the same since creation)

Lets say I have a class called DataManager that keeps track of Car objects in an static ArrayList.

public class DataManager {
public static ArrayList<Car> carList = new ArrayList<>();

In Activity 1, I add a Car Object to the carList, and then parcel the Car and send it to Activity 2 to be used.

public Activity1 extends Activity {
protected void onCreate(....) {
Car originalCar = new Car("Red","0");
DataManager manager = new DataManager();
Intent i = new Intent(Activity1.this, Activity2.class);

Because Java passed by value when the car object is received in Activity 2, a new object is created and the hashCode will not be the same as the original object preventing Java.Object .equals() from comparing correctly.

public Activity2 {
protected void onCreate(....) {
Car parcelledCar = intent.getParcelableExtra("parcelledCar");

DataManager manager = new DataManager();
manager.carList.indexOf(parcelledCar); // RETURNs -1
// because the (.equals inherited from Java.Object compares
// addresses which are not the same)

I realize that overriding the default .equals() might help in this case, but I am not sure how objects could be compared if all properties of the Car object are not guaranteed to the stay the same through the application life cycle.

For example:

public class Car {
private String colour;
// Different cars can have the same colour
private int timesDriven;
// Value is dynamic and subject to change throughout application

Something like a GUID used in a database would be nice, but in my particular use case I am not using a database and I am not aware of any built in android utilities to create a GUID like identifier that is constant across parceled instances of an object (if that makes sense)?

Answer Source

The fact that the Car object received by Activity 2 is not the same instance as the original Car object has nothing to do with Java pass-by-value. That is caused by the serialization/parcel done by Android. Java pass-by-value would pass the reference to the object by value, but it would be the same object instance.

If the Car objects are always created in the DataManager first, then you can add an id field to the Car object, and assign the value using an AtomicInteger maintained by DataManager. You'd then replace the List with a Map of id to Car object.

Now you can just send the id between activities, and lookup the Car object.

Basically, you've turned the DataManager into a simple in-memory database.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download