Skip to content Skip to sidebar Skip to footer

Android Java: Global Variables Through Subclass; Can't Launch App?

I've been reading up examples on how to do this, trying to piece together a functioning example from posts on this site and others. I'm sure I'm missing something small, but as a

Solution 1:

You are calling getApplicationContext() in your class definition, which is too early in the activity lifetime and results in a nullpointer exception. Move the assignments to your onCreate() function and it should work as expected.

Solution 2:

Please check this article about activities and their lifecycle : http://developer.android.com/reference/android/app/Activity.html#ActivityLifecycle

Your activity should look like this:

publicclassMainActivityextendsActivity {

    GlobalVars myVars;      
    TextView myText;


    @OverridepublicvoidonCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        myVars = ((GlobalVars)getApplication());
        myText = (TextView) findViewById(R.id.myText);
        myText.setText(myVars.getMyString());
    }

    @OverridepublicbooleanonCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        returntrue;
    }
}

Solution 3:

Add these lines in oncreate().. GlobalVars myVars = ((GlobalVars)getApplicationContext());TextView myText = (TextView) findViewById(R.id.myText);

Post a Comment for "Android Java: Global Variables Through Subclass; Can't Launch App?"