Prakash Jackson
Prakash Jackson

Reputation: 435

How to declare a variable that can be accessed by all the classes in android?

I'm a new to android please help me with the following.

I'm having an integer value which stores the id of a checked radiobutton. I need to access this value throughout the various classes of my app for a validation purpose.

Please let me know how to declare and access this variable from all the classes.

Thank you.

Upvotes: 1

Views: 4846

Answers (3)

Ruban
Ruban

Reputation: 1534

following singleton pattern is the only way to do this.in java/android if u create a instance for a class every time it create a new object.what you should do is

1.create a model class and  make its as singleton 
2.try to access the modelclass from every class



public class CommonModelClass 
{
    private static CommonModelClass singletonObject;
    /** A private Constructor prevents any other class from instantiating. */

    private CommonModelClass() 
    {
        //   Optional Code
    }
    public static synchronized CommonModelClass getSingletonObject() 
    {
        if (singletonObject == null) 
        {
            singletonObject = new CommonModelClass();
        }
        return singletonObject;
    }


    /**
     * used to clear CommonModelClass(SingletonClass) Memory
     */ 
     public void clear()  
      {  
         singletonObject = null;  
      }


    public Object clone() throws CloneNotSupportedException 
    {
        throw new CloneNotSupportedException();
    }

    //getters and setters starts from here.it is used to set and get a value

    public String getcheckBox()
    {
        return checkBox;
    }

    public void setcheckBox(String checkBox)
    {
        this.checkBox = checkBox;
    }   

}

accessing the model class values from other class commonModelClass = CommonModelClass.getSingletonObject();

commonModelClass.getcheckBox(); http://javapapers.com/design-patterns/singleton-pattern/

Upvotes: 1

Akshay
Akshay

Reputation: 2534

You can declare your integer variable as static and access in any class.Like this

    class A{

       static int a;
        }

You can access in another class like this.

   class B{

    int b = A.a; 
    }

Upvotes: 0

Bhoomika Brahmbhatt
Bhoomika Brahmbhatt

Reputation: 7415

U can use:

MainActivity.class

Public static int myId;

In other Activities.

int otherId=MainActivity.myId;

Upvotes: 1

Related Questions