简体   繁体   中英

Declaring variables as static within MainActivity and accessing them from other classes

Many times when I have been developing android apps, in order to access some important variables such as getApplicationContext() or other variables such as Buttons or Edittexts , which are normally not accessible outside MainActivity but required in some other class in the same project, I have been using this technique, that is

Within MainActivity (for getApplicationContext() case) :

private static Context context = null;

and inside the onCreate method, I do :

context = getApplicationContext();

and I then access the context ( to display a toast message , for example) by using:

Toast.makeText(MainActivity.context,"Message",Toast.LENGTH_LONG).show();

in my other class. Similarly to get or set the text in an EditText variable and so on.

My questions are:

1)Is this the best method for my problem definition?

2)If no, is there a better way?

3)if no, what are the disadvantages of this technique?

3)Can the same technique be extended to functions in the Mainctivity?

EDIT : I do not require another Activity here, rather I am just splitting the task of the app into separate classes (or objects).

My questions are:

1)Is this the best method for my problem definition?

no this is not the best way of solving this.

2)If no, is there a better way?

yes to save static information you should be using something like a headless fragment so that the android framework can handle the garbage collection on unused classes and data

3)if no, what are the disadvantages of this technique?

disadvantages are many :) firstly memory leaking cause that static var cant be garbage collected at all so it stays in memory. secondly you should not use edit texts from the main activity somewhere else cause there is no garantee that the mainactivity will still be there cause if you move away from it android might kill it to save memory. all screens should be selfcontained and data must be transfered with intents and Bundles()

3)Can the same technique be extended to functions in the Mainctivity?

create seperate helper classes that sit within a static class like helpers. MainActivity is not a static class and shouldn't be a static class

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM