Creating Global Session Variables for all Activities Android Example

Here is an Android example of how to share variables through out your activities and your project. There is many ways including preferences, extending from a base activity or using  a database to share variables. I like this one because it can be accessed through the whole project and it is easy to implement. The down side is that the variables are only available through a session. For example if the user restarts the application then all the variable will also be cleared. So they can be viewed as session variables.

 

 

GlobalState Class:

-Note this extends Application

import android.app.Application;

public class GlobalState extends Application{
	
	 public File sd = null;
	 boolean refresh = true;
	 pictureData [] picturemarkers = null;
	 
	 public File getFilePath(){
		 return sd;
	 }
	 
	 public void setFilePath(File sd){
          this.sd = sd;		 
	 }

	 public pictureData[] getPictureData(){
		 return picturemarkers;
	 }
	  
	 public void setPictureData(pictureData [] picData){
		 picturemarkers = picData;
	 }
	 
	 public void setRefresh(boolean refresh){
		 this.refresh = refresh;
	 }
	 
	 public boolean getRefresh(){
		 return refresh;
	 }
			 
}

ExampleActivity Class:

public class ExampleActivity extends Activity {

        GlobalState gs;

	public void onCreate(Bundle savedInstanceState) {
              gs = (GlobalState) getApplication();
        }

        public void examples(){  
            File temp = gs.getFilePath();
            if(gs.refresh()){
                gs.setRefresh(false);
             }
        }
} 


Manifest

-I do not fully understand why but it is needed for it to work.  Set the ‘name’ of your application to the path where the file is located.

<application
        android:name="your.package.name.GlobalState"
  • http://a2bikes.co.uk/ A2 Bikes

    It works, thanks!

  • Mathijs Segers

    About the I do not fully understand why, is because if you don’t provide this in the Manifest, it will use a generic Application class instead. Since the Application is the instance the app runs on.


Graveyard Database Logo

Has everything you want to know about grave yards. Plus has many celebrites and world leaders graves. Pssst it is my other site

Google + Profile
Check out Android Photo Mapping, its a app/site I been working on
  • wholesale nfl jerseys
  • wholesale nfl jerseys china
  • wholesale sports jerseys