How to use global variables in android? -Part 2

By | February 20, 2012

Hello all….

In a previous post I showed a method to share global variables across your android application.
Those were done using a static class.
Now today I will show you another way of sharing global variables across the application

Check these posts for sharing data across the application.
1. http://coderzheaven.com/2011/05/global-variables-in-android/
2. http://coderzheaven.com/2011/05/global-variables-in-android%e2%80%a6/
3. http://coderzheaven.com/2011/03/passing-data-between-intents-in-android/

Now in this method. first create a class named “GlobalClass” and extends the “Applictation” class.

This is how it will look like.

package com.coderzheaven.pack;

import android.app.Application;

class GlobalClass extends Application {

	  public static String myVal;

}

Inside which I have a variable named “myVal” which is a string. This is the global string variable that I am using to pass values across the application.

Now the main java class
Here I am using two activities just to demonstrate the sharing of global variables across the application.
Here is the first activity.

package com.coderzheaven.pack;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class GlobalVariablesDemo extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        // Assigning some value to the global variable //
        GlobalClass.myVal = "Hello from CoderzHeaven";

        Button b = (Button)findViewById(R.id.Button01);
        b.setOnClickListener(new  OnClickListener() {
			@Override
			public void onClick(View v) {
				startActivity(new Intent(GlobalVariablesDemo.this, SecondClass.class));
			}
		});
    }
}

This line shows how to assign value to a global variable.

GlobalClass.myVal = “Hello from CoderzHeaven”;

Now the second activtiy.

package com.coderzheaven.pack;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class SecondClass extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.second);

        System.out.println("Accessing the global string : " + GlobalClass.myVal);

        TextView tv = (TextView)findViewById(R.id.tv);
        tv.setText("Global String : " + GlobalClass.myVal);
    }
}

This is how you access the global variable.

GlobalClass.myVal

That’s all done.

Now go on and run the application.

Please leave your comments if you like this post.

Leave a Reply

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