Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

define constant to be used by all activities in an application : android

Tags:

android

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.

like image 900
Android_enthusiast Avatar asked Mar 24 '11 17:03

Android_enthusiast


People also ask

What is a constant in Android?

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.

What is activities Android application?

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.


2 Answers

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.

like image 44
Venky Avatar answered Oct 05 '22 03:10

Venky


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.

like image 148
LeffelMania Avatar answered Oct 05 '22 04:10

LeffelMania