1

I have read some articles about how to use/extend the Android Application class but I am still kind of unsure if I can use it for my needs.

In my Application, on startup, i read a JSON configuration file. This configuration file contains some basic infos about an external device. Because I need this infos in several other fragments/activities I simply store an object representation of this json file as a member variable of my Application class.

public App extends Application {

   private ConfigurationContainer configuration;
   ...

   getters / setters
}

When I need it i call getApplication().getConfigurationContainer().

Is this OK for my needs?

Moonlit
  • 5,171
  • 14
  • 57
  • 95

2 Answers2

1

Yes, It is ok. Follow this steps.

1.Override onCreate() method and load all the json configuration in this method.

          public App extends Application {
          private ConfigurationContainer configuration;
          public void onCreate(){
                 super.onCreate();
                  // load json configuration.
               }
             // getter setter
             }
  1. Declare this class in manifest file.

      <application android:name="com.packageName.App">.
    
  2. Use this configuration in all your activity.

     App ap = (App)getApplication();
     ConfigurationContainer conf = ap.getConfigurationContainer()   
    
Sanjay Kushwaha
  • 70
  • 2
  • 10
1

Yes it is reasonable to store globally scoped variables (or objects) in your Application class. You should be careful that you are not storing too much data here, as it will consume memory that is never recovered as long as your app is running.

Your concept is fine, but there are some nuances about using the Application class in this way, it is suggested that you create a Singleton class (instantiated by your Application) to store values like this.

Here is a great SO related to this: Android Application as Singleton

Community
  • 1
  • 1
Booger
  • 18,579
  • 7
  • 55
  • 72