Variable accessible from the whole app

2

Is there any way to have a variable and that it can be accessible from the whole app? Not only from the activity that I am in.

    
asked by Rodrypaladin 11.12.2018 в 18:45
source

2 answers

1

You can create a public class , in fact it is common to have this in projects and the variables to be accessed must be defined as static :

public class GlobalInfo {

    public static final String PREFS_CONFIG = "Breaking_News";
    public static final String PREFS_SYSTEM = "GR_System";

    public static final int MINUTE_MILISECONDS = 60000;
    public static final int IDPUB = 2001;

    ...
    ...
    ...   


}

From another class you can access these values, for example:

 Long period = GlobalInfo.MINUTE_MILISECONDS;
 String nombreConfiguracion = GlobalInfo.PREFS_CONFIG;

Another way is that your class that will contain the "global" variable, extend from ** Application : **

public class MyApplication extends Application {

    private String valorInicial = "Breaking_News";

    public String getValorInicial() {
        return valorInicial;
    }

    public void setValorInicial(String valorInicial) {
        this.valorInicial = valorInicial;
    }
}

Obviously this class must be defined in our file AndroidManifest.xml

<application
   android:name=".MyApplication"

   android:icon="@mipmap/ic_launcher"
   android:label=""@string/app_name">

and in this way you can access the variable:

String valor = ((MyApplication) this.getApplication()).getValorInicial();
    
answered by 11.12.2018 / 19:13
source
1

You have to create a class with public access and define the attributes as a static variable, I'll attach an example:

public class Globales {
    public static String nombres = "Juan";
    public static String apellidos = "Perez";
}

Later you can call it from an activity, fragment, etc.

// Imprimir valores de inicio
Log.d("SO", Globales.nombres);
Log.d("SO", Globales.apellidos);

// Podemos modificar su valor
Globales.nombres = "Juan 2";
Globales.apellidos = "Perez 2";


// Imprimir valores modificados
Log.d("SO", Globales.nombres);
Log.d("SO", Globales.apellidos);
    
answered by 11.12.2018 в 19:03