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 class MainActivity extends Activity
Application instance is created by the Android run time when the first application starts.
public class MyApp extends Application
{
public String mStateData = "Hello Application";
private static MyApp singleton;
public static MyApp getInstance()
public String mStateData = "Hello Application";
private static MyApp singleton;
public static MyApp getInstance()
{
return singleton;
}
@Override
public void onCreate()
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>
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:
{
@Override
public void onCreate(Bundle savedInstanceState)
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Log.d("mStateData variable access from MyApp: ", MyApp.getInstance().mStateData);
}
}
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Log.d("mStateData variable access from MyApp: ", MyApp.getInstance().mStateData);
}
}
No comments:
Post a Comment