Home » Android » android – Sharing an object between activities

android – Sharing an object between activities

Posted by: admin June 15, 2020 Leave a comment

Questions:

I have a Weather app with four Activities. The main/launcher activity is ‘invisible’ using…

android:theme=”@android:style/Theme.Translucent.NoTitleBar”`

…and is simply used to do a few checks (whether this is a new install, whether a network connection is available etc) before firing off one of the other Activities. The other Activities are UI-oriented – two simply display weather data pulled from a website and the third to provide a location ‘picker’ so the user can choose which area to show the weather for.

However, all four activities make use of a WeatherHelper object which basically does everything from checking for available SD card storage to maintaining preferences and pulling/formatting website pages.

So, my question(s)…what is the best way to have one instance of WeatherHelper which can be used by multiple activities and where/how are best to create it in my case?

I’ve been an OO programmer for a lot of years but I’m very new to Android and the design concepts – I’ve read a lot on the Android Developers site over the past weeks but I’ve stalled trying to decide on this.

Any ideas gratefully received.

How to&Answers:

I would store shared information in you Application object. Subclass this and add any extra initialization and data there. You can get your application using getApplication() from your activity, which you can cast to your specialized version and access the shared data.

I would also avoid launching the special startup activity if possible and do the work in your Application’s onCreate() override.

Answer:

Well, your question has been answered, but it seems like it would be much simpler to instantiate your WeatherHelper object in the onCreate() of the Activity that has the launcher intent, and make the WeatherHelper static.