-2

In my project,i need to use some UI object (such as Textview) that Between two Independent class or two activity;

In this case,to avoid repeating the code which get UI object,I want use an static Ui object to instead. Of course ,i am also thinking about the safty of static object in App life cycle; But The article of android-static-object-lifecycle clear up my doubt;

the value of the static variable will persist when you switch to a different activity of another application and none of the below three happens.

1. the class is unloaded

2. the JVM shuts down

3. the process dies

In my Opinion ,using static object no only safty but also more convinece to use in different class; But In fact it is rarely see in others project. Is there any Disadvantage to use static ui object?

Please post your suggestions on this... Thanks in advance

Community
  • 1
  • 1
tao.weng
  • 37
  • 6
  • *to avoid repeating the code which get UI object* ? just pass the textview instance to the class that needs it. If the other class is also an activity, it doesn't need this textview since it is not his – Tim Oct 10 '16 at 13:03
  • you are right,pass instance can handler this.But when there are many ui instance need pass, how can i code it more easy? – tao.weng Oct 11 '16 at 13:11

1 Answers1

2

Each UI element will need a context. When you provide this (this being an Activity subclass for example) the element will hold a reference to your activity. This is bad because activity instances may be recreated by the runtime (for example when the screen rotates). In those cases the older instance will still remain in the memory (as it cannot be garbage collected) because your UI element has a reference of it (via this). Hence, it is advised not to use static UI elements.

Shaishav
  • 5,282
  • 2
  • 22
  • 41
  • thank you for your explain.now i know it can not work in other activity class.But how about use in an thread(for example i have an mapview instacne and i need to updating by an thread)?? – tao.weng Oct 11 '16 at 13:26
  • @tao.weng MapViews are heavy and I'd suggest against making them static. You should look into other ways of communicating with threads (for eg. say an interface). – Shaishav Oct 11 '16 at 13:43