0

I'm not sure if what I'm asking is correct, so please forgive my ignorance.

I need to use an object initialised in the main activity in another one. I serialized the object class with implements Serializable and sent it to the new activity putting into an extra, retrieving it later with intent.getSerializableExtra.

The other way would be access directly the previously public declared object from the activity using the following:

MainActivity mainActivity = (MainActivity) this.getParent();
Object object = mainActivity.object;

Is any of this correct?

If yes, which one?

If both which is better?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Oiproks
  • 764
  • 1
  • 9
  • 34
  • 1
    `this.getParent()` will only work in [special cases](https://stackoverflow.com/questions/6102772/android-activity-getparent-always-returning-null). Intent extra would be a "standard way". – Markus Kauppinen Oct 04 '19 at 13:46

1 Answers1

0

I am not sure if you have the right design in the first place. Trying to cast the MainActivity is not a good practice. This is a step towards making it a God class.

I am not sure what is the point of sending a Serializable object. In general more likely is to use some primative values or Strings. If is something heavy why to pass it? And what bothers me more is that you are saying that you want to use something "initialized " in the MainActivity which makes me think that you are not trying to pass data, but access the state of MainActivity from another Activity which is a bad practice.

The Views needs to present data and notify for events like clicks some "other code". Nothing more. You can have some singleton class and change its state as appropriate depending on the actions in the First Activity. Then from the Second Activity, let's say you have MVVM, you create the ViewModel and observe it, the ViewModel in its init{} can call the shared singleton and can propagate the data back to the second Activity through LiveData, or better just to tell it what to "show" to the user.

I hope it helps.

Yavor Mitev
  • 1,363
  • 1
  • 10
  • 22