Raigex
Raigex

Reputation: 1215

Accessing a variable from anywhere in an Application(Android)

Is it possible to create a variable in the starting activity (eg : Book class in Activity 1) and have it available anywhere in the application (eg Book class in Activity 3 , 4 &5) without actually passing it.

I am asking because my xml handler creates a series of objects be it also updates the xml file after any change is made to the object.

Upvotes: 1

Views: 867

Answers (2)

GedankenNebel
GedankenNebel

Reputation: 2587

Implement a class, for example with the name GlobalVariables, which extends Application.

public class GlobalVariables extends Application

In your AndroidManifest.xml do this in the application tag:

<application android:label="@string/YourAppName" android:icon="@drawable/YourIcon"
                 android:name=".activities.GlobalVariables.">

Don´t forget the package path for declaring your class (similar you do for adding activities to manifest file).

Then you can access this class and its variables or methods from everywhere of your application. Do this in the onCreate method of any Activity:

GlobalVariables globalVariables = (GlobalVariables) getApplicationContext();

The Class extended from Application (e.g. our GlobalVariables here) will be created with the start of your app and will be available until the app will be destroyed.

You can have a HashMap or something, else where you can store your desired variable, in the GlobalVariables class. Push the variable from your first Activity into the GlovalVariables and pull it from the second trough getting an instance to the GlobalVariables. Like this (once again):

GlobalVariables globalVariables = (GlobalVariables) getApplicationContext();

Upvotes: 1

Ted Hopp
Ted Hopp

Reputation: 234795

You can create a static variable. As long as it's declared with appropriate access (e.g., public) it will be directly available to any activity in the same process. (This will be the default; you need to do extra work to get an activity into a separate process.)

It's common to separate out such global variables into a separate class.

However, be aware that if your app is pushed into the background, there's a chance that the process will be killed off and re-created. In that case, any data stored in static variables will be lost. Alternatives include using SharedPreferences, a data base, or a ContentProvider.

Upvotes: 4

Related Questions