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"
Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s