Preferred Android template for storing objects that require global access

I've read similar questions but haven't found a better solution yet. So, for example, I load user data from the server when the application starts. The information is later used in many components of the application. I don't feel comfortable storing it in a singleton (for example in an application) and making it globally acceptable. Other options I could think of is to store it in general preference as JSON, or store it in a database. But these approaches can lead to some performance results. How do you solve this common problem?

+3


source to share


3 answers


Seems like the best approach is to extend the Application class and add your globals, another Stack Overflow question below might help:

Android Global Variable

Also, if you look at the javadoc class of the Application class, it says that it is used to consume the global application.



Base class for those who need to maintain the global state of the application. You can provide your own implementation by specifying its name in your AndroidManifest.xml tag, which will cause this class to be generated for you when the process for your application / package is created.

See the full Javadoc here

+2


source


If you want to access data for all activities, you can try making a base activity that extends the activity and then use the base activity as a base class for other activities.

public class MainActivity extends BaseActivity

      

Then for BaseActivity



public class BaseActivity extends Activity

      

In BaseActivity store all your values ​​as global variables, these variables can then be passed by every activity that extends the base activity

0


source


I think you should use Shared Preferences to make the data available throughout the application. Alternatively, you can store your data in internal memory or cache. Depends on the amount of data, depends on whether you want it to be available between sessions.

Read http://developer.android.com/guide/topics/data/data-storage.html to see your options.

0


source







All Articles