Declaring a global variable for use in all activities

I create a custom class in the main class of the application. Allow My mainAccount.

Now I am creating a lot of actions. I want a variable mainAccountin every action, how can I do this? One way is to insert an intention and move on to each action. Is there a better way, for example to make global etC?

Regards

+5
source share
4 answers
+6

Singleton classes. , - .

public class Singleton {
   private static Singleton instance = null;
   protected Singleton() {
      // Exists only to defeat instantiation.
   }
   public static Singleton getInstance() {
      if(instance == null) {
         instance = new Singleton();
      }
      return instance;
   }
}

, , :

Singleton var=Singleton.getInstance();

, . , , , , .

+6

, , .

:

public abstract class BaseActivity extends Activity
{
  //static variables
  // static methods
}

BaseActivity :

public class HelloAndroid extends BaseActivity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }
}
+4

You can use the "singleton" class or the "static" class (unless you need to initialize it, create instances, or inherit or implement interfaces).

Singleton Class:

   public class MySingletonClass {

        private static MySingletonClass instance;

        public static MySingletonClass getInstance() {
            if (instance == null)
                instance = new MySingletonClass();
            return instance;
        }

        private MySingletonClass() {
        }

        private String val;

        public String getValue() {
            return val;
        }

        public void setValue(String value) {
            this.val = value;
        }
    }

String s = MySingletonClass.getInstance (). getValue ();

Static class:

public  class MyStaticClass {
    public static String value;
}

String s = MyStaticClass.value;

0
source

All Articles