Wednesday, May 9, 2012

How to use global variables in android?


How to use global variables in android?




Now today I will show you another way of sharing global variables across the application
Now in this method. first create a class named “GlobalClass” and extends the “Applictation” class.
This is how it will look like.

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.

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 android 
        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 android”;
Now the second activtiy.
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.



2 comments:

ALBIN said...

great.i want more information about global variales .so please help me.(albinrath@gmail.com)

ALBIN said...

Again i want 3 columns in the listView like qty,item,price.i heard custum listView is posible.plz give examples of custum listview related 3 columns.