I want know i pass a variable via Intent to another activity and that activity changes that variable, will it reflect in original activity without passing back the intent. If answer is no then is it better to use global variable using application then passing intent and getting back data. in my program, i am having round 5+ activities and all of them need to access a list of class objects. any recommendations apart from above
1 Answers
Create your own extension of Application
to store the state of your app and share data between the different activities that make up your app. The Application
acts as the context for your whole app and Android guarantees there will always only be one instance across your app. Hence it works similar to defining your own Singleton, but using Application
will allow Android to take control of the life cycle of your shared data and basically do the memory management for you.
To summarize:
- Create your own subclass of
Application
. - Specify that class in the application tag in your manifest.
After this you will be able to safely cast the result of all call to getApplication()
(from an Activity
instance) and getApplicationContext()
(from any Context
instance) to the subclass you defined in step #1. This means you can use any getter/setter method defined in your application extension to store/retrieve data.
-
is it better way than passing data by Intent? – Hannibal09 Sep 06 '12 at 03:04
-
That depends on the purpose of the data. If you're after making the data centrally available (read: share data and state between different activities) them I'd definitely go with the `Application` approach. Consider it kind of being your apps 'model'. If you only need the data locally or once, there's no point in centralizing it, so you might as well use an `Intent`. Your description suggests the first applies to your case. – MH. Sep 06 '12 at 04:43
-
i have my centerly data as list of class object whihc also contains list. now when i use classAList.get(position).classBList. but this way when orginal get updated by another activity its referance not get changed. can you help in that – Hannibal09 Sep 07 '12 at 14:54
-
I'm sorry but I can't follow your description. Your original question was rather generic whereas what your describing here is quite specific. I suggest you start a new Q&A and provide code snippets to clarify on the exact problem(s). – MH. Sep 09 '12 at 19:09