I want to define constants which can be used by all activities in an application. What is the best way to do it.
Is extends Application only way of doing it, since I dont want to declare same constant in all the classes.
Magic constants are a response to the ever-growing number of APIs in the Android framework, where the state, type of a component, or an action are chosen by providing an int or String constant. For example, setting view visibility with int constants or requiring a system service with String constants.
An activity provides the window in which the app draws its UI. This window typically fills the screen, but may be smaller than the screen and float on top of other windows. Generally, one activity implements one screen in an app.
Simple answer declare that Variable as STATIC FINAL and use that constant in all activity's by the name of you activity.constantname eg:activity1.name
it will take same values whenever you use it, also it will change globally.. takes same values no matters from which Activity you are accessing It.
There are two ways I've used that are effective:
1) Make an interface called Constants or Globals or whatever you want. Define your constant values in that class and make them all public and final. (They have to be public by definition of an interface, but be sure they're final as well). Now simply declare your Activities and any other classes to implement your Constants interface. Now they all have access to the same global values.
2) Make a class Constants instead of an interface. Define all your constants as public static final. Now you can reference all your constant values via Constants.VARIABLE_NAME in any class in your application.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With