Global declaration of variable in android

浪子不回头ぞ 提交于 2020-01-22 15:26:47

问题


I am new to android development, I am parsing a xml file through SAX parser and storing the parsed data into a string.Now i need to use that string in another class, so i need to know how to call that parser in the new class. thanks in advance


回答1:


I always make a class that contains all of my globals and call it "Constants.java"

final public class Constants//final to prevent instantiation
{
    public static final String SOME_STRING = "0.04";
    public static final int SOME_NUMBER = 5;
    public static final float METERS_PER_MILE = 1609.344f;

    //private constructor to prevent instantiation/inheritance
    private Constants()
    {
    }
}

to use one of these in your code, be sure to import the class and use:

Constants.SOME_NUMBER




回答2:


You can use a static variable and can access it any where in the application

public static int myVar = 1;

access it by ClassName.myVar




回答3:


You can use intent to pass the value. Also,you can use the manifest.xml to make a gloable variable.




回答4:


Using the android application extension is NOT multi-process safe, as described here: How to declare global variables in Android? Note the first response. He defines how to extend the application itself but makes a note that "this method offers no way easy way of persisting the global state. If your application finds this necessary you should be using some sort of store; see the Android docs for a variety of methods." I have also seen other posts that state that between processes this method needs to be modified slightly, but I think it's possible. Let me know if I understood that wrong...




回答5:


You should use application object to get a global variable, you can see a working example here http://www.helloandroid.com/category/topics-covered/application-object

Application class documentation is stated here http://developer.android.com/reference/android/app/Application.html



来源:https://stackoverflow.com/questions/5659879/global-declaration-of-variable-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!