I have a simple doubt. In android it been said almost everywhere that to pass a String or int or anything u supposed to use Intent and use putextra() or whatever to pass it over that next activity where as i can create a static object and access it from any activity
There has to be some reason behind using the intent to do so, can anyone please clear me why we need intent to pass an object from one activity to other where we can do it as normally as we do it in java.
Because we don’t think of Activities in a static context. Activities have life cycles, so we try to incorporate our data within this life cycle rather than circumventing it.
There’s nothing directly wrong with just using a static variable, but there could arise some problems. Say, for instance, you display multiple instances of an
Activity. TheStringyou need for the childActivitymight be different than what you previously needed, so when navigating backwards to a previous instance of thatActivity, the value is not what you were expecting.Passing the
Stringin through theIntentalso makes theActivityindependent. OneActivityshould not be designed in a way that it is tightly coupled with another. Passing data through theIntentmeans that anyActivitycan start thisActivityas long as it passes in the correct data.That said, there are cases where using a statically accessible variable are reasonable, such as for constants values that won’t change and are accessed by multiple parts of your app, or for any data that multiple Activities might need.