Java – Class instance while retaining variables between activities

androidandroid-developmentjava

First: This is for a project that is already deployed, and requires a solution that isn't "rewrite how the whole thing works"!

I have a "record detail" screen of sorts that is storing the corresponding RecordID in a static variable. Within this screen you can drill down, which passes the RecordID into a bundle and is retrieved by the new activity in order to display and edit the information appropriately. Going back to the original detail screen works as intended.

Now I must incorporate a feature that utilizes a new instance of this same detail screen; but if I spawn a new instance of this detail activity and pass on the RecordID and then go back to the first instance of the detail screen, that RecordID is now the same as the one that I passed to the second instance. This is due to the RecordID being static, I'm guessing.

When I make this RecordID no longer static, I can freely create a new instance of the detail class and go back and forth with the correct RecordIDs in each instance. However… this makes it so when you drill down into an activity within the detail and come back, the variables are now null.

What is the best way to fix this situation?

  • I don't think using savedInstanceState would work since the activity isn't actually going to be destroyed. I tried this and the method isn't even called.
  • I thought about doing startActivityForResult and just passing the record ID back to the detail screen, but that seems horrible inefficient.

Best Answer

You are correct in thinking that being static was causing the issue. Along with preventing a second instance's creation static reference means that there is no actual instantiation, you just reference the class itself. The reason that you are getting nulls when you back out is because you do not have a reference to the object above you.

Think of it like a tree navigation. If you start at a leaf and go up to the parent of the parent of the parent then you get to a point where you don't remember the way back and there are several possibilities. You need to store references up the chain. I would use a stack to hold the references as you move deeper. Then when you come back up then you can just pop the node off the stack.