0

I am trying to pass an object from an activity to another activity. Here is what i do:

MyApplication.db= dbToOpen;
Intent i = new Intent(mContext, OpenDbActivity.class);
i.putExtra("PARENT_GROUP", dbToOpen.root);
mContext.startActivity(i);

Here, MyApplication is the class that extends application, and db object is a static object. My extra object dbToOpen.root is an object of the class DBGroupv1.

Then i get this extra in onCreate method of OpenDbActivity class:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_opendb);
    db = MyApplication.db;
    groupToOpen = (DBGroupv1) getIntent().getSerializableExtra("PARENT_GROUP");

}

Then i try this boolean expression:

MyApplication.db.root == groupToOpen

and it returns false. When i look at the objects dbToOpen.root and groupToOpen, every single value of the variables inside those objects are the same. But they are are different objects. Why is this happening? Is it because of casting, or does Intent.putextra() method passes a copy of an object, not a reference? If that is the case how can i pass the object as a reference?(Except using static variables)

Thanks

yrazlik
  • 10,411
  • 33
  • 99
  • 165

1 Answers1

1

You should use the .equals()-method to compare instances of objects. if you use == you will only get true if the two objects are exactly the same reference. Since the instance in your intent is newly created when deserialized from the bundle, it is no longer a reference to the same instance (although the two objects contains the same data).

So, instead of

MyApplication.db.root == groupToOpen //bad

use

MyApplication.db.root.equals(groupToOpen) //good

Also make sure that if you made the root-object, you implement the equals method properly, so it takes all appropriate variables into consideration.

You can read a bit more here: What is the difference between == vs equals() in Java?

Community
  • 1
  • 1
Jave
  • 31,598
  • 14
  • 77
  • 90
  • Thanks, but actually i am not confused about == vs equals, I used == intentionally to see whether these two objects are the same reference. It looks like putextra method copies the object, does not pass a reference, but i want to pass it as a reference between activities, not the copy of the object – yrazlik May 21 '14 at 07:29
  • They are not the same reference. The intent extra uses a `bundle`, which represents data as a string - other objects are serialized. Deserializing them creates new references. If you want the same reference, why not just get it from `MyApplication.db`? – Jave May 21 '14 at 07:39