Android global variable

前端 未结 14 1082
眼角桃花
眼角桃花 2020-11-21 23:32

How can I create global variable keep remain values around the life cycle of the application regardless which activity running.

相关标签:
14条回答
  • 2020-11-22 00:09

    Use SharedPreferences to store and retrieve global variables.

    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
    String userid = preferences.getString("userid", null);
    
    0 讨论(0)
  • 2020-11-22 00:18

    Easy!!!!

    Those variable you wanna access as global variable, you can declare them as static variables. And now, you can access those variables by using

    classname.variablename;

    public class MyProperties {
    private static MyProperties mInstance= null;
    
    static int someValueIWantToKeep;
    
    protected MyProperties(){}
    
    public static synchronized MyProperties getInstance(){
        if(null == mInstance){
            mInstance = new MyProperties();
        }
        return mInstance;
    }
    

    }

    MyProperites.someValueIWantToKeep;

    Thats It! ;)

    0 讨论(0)
提交回复
热议问题