Android global variable

前端 未结 14 1086
眼角桃花
眼角桃花 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-21 23:52

    Try Like This:

    Create a shared data class:

    SharedData.java

    import android.app.Application;
    
    /**
     * Created by kundan on 6/23/2015.
     */
    public class Globals {
    
    
        private static Globals instance = new Globals();
    
        // Getter-Setters
        public static Globals getInstance() {
            return instance;
        }
    
        public static void setInstance(Globals instance) {
            Globals.instance = instance;
        }
    
        private String notification_index;
    
    
        private Globals() {
    
        }
    
    
        public String getValue() {
            return notification_index;
        }
    
    
        public void setValue(String notification_index) {
            this.notification_index = notification_index;
        }
    
    
    
    }
    

    Declared/Initiaze an instance of class globally in those classes where you want to set/get data (using this code before onCreate() method):-

    Globals sharedData = Globals.getInstance();
    

    Set data:

    sharedData.setValue("kundan");
    

    Get data:

    String n = sharedData.getValue();
    

提交回复
热议问题