Declare Global Variable In Android via

I am creating an application which requires login. The problem comes when I want to store the application state (e.g. whether user has login or not). Storing state in activity class is almost it is hard to make it persistent. For example, rotating the screen will literally wipe out the application state. Also when the phone keyboard slides the login form appears again and again.

Indeed this is one main problem people typically encounters when trying to save stat across several Activities and all parts of application. A static variable is a common Java way of achieving this. on the other hand, oe solution I could think of is to prevent screen rotation in relevant activity claSS as well as phone keyboard via

<activity android:name=".MainActivity" android:label="@string/app_name"
android:screenOrientation="portrait" >
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />

However, after much digging, I have foind much elegant way to achieve this kind of desired persistence by creating a subclass of before specifying the class in the android manifest file.

In this case, Android will automatically create an instance of that application class and make it available to entire application.

Example of such class is


public class CombankDroid extends Application {

private boolean isLogin;

public boolean isLogin(){
return isLogin
public void setIsLogin(boolean b){
isLogin = b;


Of course you need to declare this CombankDroid class that extends application in Android manifet at application tag.

android:label="@string/app_name" >


You can access CombankDroid application class from any context using the Context.getApplicationContext() method. Also, Activity class also provides a getApplication() which has same effect.


class Anyhow extends Activity {

public void onCreate(Bundle b){

CombankDroid combankDroid = ((CombankDroid)getApplicationContext());
//CombankDroid combankDroid = (CombankDroid) getApplication();

// Don’t start the main activity if we don’t have credentials
if (!combankDroid.isLogin()) {
} else {




3 thoughts on “Declare Global Variable In Android via

  1. Pingback: Daten in Activity bei Layoutwechsel erhalten -

  2. Pingback: direct Global viable access using an "Application" class? | Mobile Techq

  3. Pingback: How do I make global changes throughout my app in Android? | PHP Developer Resource

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>