Current Android Release version:
Version Code: Pie
Version: 9
API level: 28

Android Application class

Application class is the base class where you can maintain global variables.Sometimes you want to store data, like global variables which need to be accessed from multiple Activities - sometimes everywhere within the application. In this case, the Application object will help you.
Application instance is created by the Android run time when the first application starts.

import android.app.Application;

public class MyApp extends Application 

{

          public String mStateData = "Hello Application";
          private static MyApp singleton;
          public static MyApp getInstance()
          {
                  return singleton;
          }
          @Override
          public void onCreate() 
          {
                  super.onCreate();
                  singleton = this;
          }
}

Then need to add this newly created class in app manifest file as follows:
<application  android:name="<your package name>.MyApp">
------------------
</application>

You can access the mStateData in your activity like below:

public class MainActivity extends Activity 
{

          @Override
          public void onCreate(Bundle savedInstanceState) 
          {
                  super.onCreate(savedInstanceState);
                  setContentView(R.layout.main);
                  Log.d("mStateData variable access from MyApp: ",                                                               MyApp.getInstance().mStateData);
          }

}

No comments:

Post a Comment