0

I have an ArrayList with more than 1000 string items in an Activity. Number of members of ArrayList does not change and no element update occurs. That Activity can be created and destroyed many times during application life time, but also it may be a few times. Also, ArrayList will be used to construct a ListView. Now I have two approaches in about ArrayList:

  1. setting its variable as static to avoid creating objects and initializing ArrayList each time in onCreate() of Activity
  2. creating and initializing ArrayList in onCreate() of Activity to avoid memory leak

I do not know which way is better or is there any other way?

hasanghaforian
  • 13,858
  • 11
  • 76
  • 167

3 Answers3

0

If you don't need to display all 1000 elements at once, you can try to use SQLite database and Cursor, which will partially load strings that you need at the moment.

Pavel Kuznetsov
  • 344
  • 2
  • 8
0

You can use singleton approach for avoiding memory leak.Below link help you to make singleton object.

ArrayList initialized/accessed using Singleton class

0

Unfortunatelly I can not honestly tell you, if there is any better way to solve your problem because you do not explain what for the mentioned Arraylist is used for. Try to explain us more about the Arraylist and we will see. If I should consider two ways you described, I have this notes:

  1. Im not sure what do you mean in this point but if i see words like string and static to avoid im not sure if its helps because this optimlization is done by java it self
  2. recreating fat objects can do some troubles to you.

At the end I recommend to you move the Arraylist outside of Activity, so it will be created only one. If Strings are different in each Activity, you still can create only as much mutations of sets as you need in whole app.

Majlanky
  • 198
  • 2
  • 9