kmalmur kmalmur - 3 years ago 129
Android Question

Is static variable really safe to exchange data between activities?

I'm working on an application that consist of a couple of activities:

  • Activity 1: main screen of an application with a "Start" button

  • Activity 2: user selects its identity from the list (more than one user is going to use the application)

  • Activity 3: user inputs password

  • Activity 4: user chooses an event from a timetable (every user has its own timetable with associated events)

  • Activity 5: user can choose an action connected with an activity.

  • Activities 6-10: user performs appropriate action.

Below some more information:

  • every activity from 6-10 have to know what user is logged in and what event has been selected

  • every activity from 6-10 has a menu that allows the user to go back to activities: 1 (to log out), 4 (to select different event), 5 (to select different action)

Since now, I've been using bundles to exchange data between activities but it seems to complicate the code as the number of actions grow (some actions use a 3-4 activities to collect data from the user). Passing all the data to every created activity doesn't seems to be nice.

I'm thinking about storing the "user name" and selected "event" as a static fields of a class. I will simplify the code very much, but I'm not sure whether this data will persist if the user let say at some point press "home button" and run another application that needs a lot of memory.

Will the data stored in static fields be safe?

Answer Source

No. You are not guaranteed that these will all exist in the same classloader, in which case you would be dealing with different copies of these classes in different places, and not accessing the same shared state.

It may happen to work now; but no it is not something I would call "safe".

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download