How to use global class variables in android

后端 未结 4 922
粉色の甜心
粉色の甜心 2021-01-26 09:12

Hi I am doing one app here. I\'m using global class varibles. It\'s working well, but if I\'m using more globalclass variables I\'m getting memory exceptions some times.

相关标签:
4条回答
  • 2021-01-26 09:39

    You can use like this

    public class GlobalVar {
    
        public int getMyVar() {
            return myVar;
        }
    
        public void setMyVar(int myVar) {
            this.myVar = myVar;
        }
    
        private int myVar = 0;
        private static GlobalVar instance;
    
        static {
            instance = new GlobalVar();
        }
    
        private GlobalVar() {
        }
    
        public static GlobalVar getInstance() {
            return GlobalVar.instance;
        }
    
    }
    

    then you can call like

    GlobalVar.getInstance().setMyVar(int);
    
    0 讨论(0)
  • 2021-01-26 09:48

    You can also use Global Variable Activity class wise. As for example

     public class SecondClass extends Activity {
    String S1,S2,S3;
    EditText edt1,Edt2,Edt3;
    Button btn1,btn2,btn3;
    //like this wat Declare all variable you want to use in your Present Activity Class
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
         setContentView(R.layout.second);
    edt1= (EditText)findViewById(R.id.tv);
    }
    }
    
    0 讨论(0)
  • 2021-01-26 09:57

    Take a look at the post Singletons vs. Application Context in Android?

    There are a lot of discussion about Singletons vs Application objects in the forum. I'm personally inclined to Application object with properties. If you dont want to keep in memory a lot of objects use a LruCache (there is a pre v11 implementation in the compatibility package) to low your memory requirements.

    Take into account you will eat the same amount of memory using Singletons than using the Application object, all objects will be keep in memory until you free them (remove any refrence to them and let the GC purge them from memory).

    0 讨论(0)
  • 2021-01-26 09:58

    First thing, you dont need Static Variable to declare global variable in Application Class,

    so Change your code to:

    class GlobalClass extends Application {
    
       public String myVal;
    
      }
    

    then whereever you need to access this data, get Application object by:

    GlobalClass global=(GlobalClass)context.getApplication();
    global.myVal="anything";
    
    0 讨论(0)
提交回复
热议问题