2

In my android project, I have a class which holds list of stream addresses (music)

Should i keep that class so i won't have to refill that list?

There may be many different screens (activities) that i will push them in to the screen or pull back from it.

Between these and screen changes ( destruction of activities ), the list will be lost...

Does this logic requires service to hold the list?

frankish
  • 6,738
  • 9
  • 49
  • 100

2 Answers2

2

You could store the list in a static singleton, or in a class extending Application. Which in turn can be accessed from the activity classes with getApplication().

When used correctly, the static singleton will function the same way as the application class, except for the fact that the singleton is accessible from everywhere, and the Application class only thru a Context.

Here a related question about what the difference between Application and singleton is.

Community
  • 1
  • 1
NickL
  • 4,258
  • 2
  • 21
  • 38
1

No, you don't need to for this.

Normally, if you had a long running class that needed to survive throughout an Activity lifecycle, putting it in a bound service would work. It would require you to transfer data via IPC. In this case, it shouldn't matter. Since you're dealing with essentially a String array, you can put it in the Intent object of the Activity you're about to start or in a Bundle which goes in to the Intent object.

On the creation of the Activity, simply open the Bundle using the Intent#getExtras() method and rebuild your list. It won't take much longer to do compared to IPC with a Service, and it should be significantly easier to maintain.

EDIT:

One thing you can try is to override the Application object. You have to specify the new entry point in the Manifest, but if you build the Singleton from the Application class and hold the reference there, it should stay alive as long as your app is running. It will be destroyed when you leave though.

DeeV
  • 35,865
  • 9
  • 108
  • 95
  • Using a static singleton class to hold the String array would work? Or the service or the new Activity creates a new one? (scope of the static object differs?) – frankish Oct 29 '12 at 13:38
  • It's unlikely to happen, but if Android flat out decides to destroy your Service to free up memory then you're out of luck. It's best to remove dependencies rather than create them. – DeeV Oct 29 '12 at 14:09
  • 1
    When a singleton is referenced correctly, it should never be garbage collected. So for example private static final Object instance = new Object(); should work just fine. – NickL Oct 29 '12 at 14:21