Search code examples
javaandroidandroid-intentandroid-activityandroid-lifecycle

Using static methods/structures to pass data between activities


If I want to pass data between activities in the same application, a) I can use an Intent or b) use a database (passing the id in the Intent instead of the full data.
But I could also use c) a class with static data structures that both activities can access in a store/fetch fashion.
What are the cons of using (c) if I don't care about persistence of the data on app restart?


Solution

  • The big cons is that the Android OS can kill your process at any time. When the process will be re-created, Android will re-create all of your activities restoring their state.

    Since Android doesn't know about how your static data should be handled, you will lose it and Activity B will be in an inconsistent state.

    I'll make an example to be clearer:

    1. Activity A is launched
    2. A button on Activity A is clicked
    3. Static data structures are being populated before launching Activity B
    4. Activity B is launched and can access the static data
    5. Android OS kills automatically your process
    6. Activity A and Activity B are restored
    7. The static data structures are not populated since they would have been populated when the button on Activity A is clicked
    8. Activity B is in an inconsistent state