0

I was wondering if I have 2 activities that needs to update and access the same object . What would be the best way to do it? Should I use Application class? Or perhaps Static variable.. Etc?

Another option I can think of is putting it in a base class that both activities inherit. I will initialize the object from shared preferences during OnResume

Snake
  • 14,228
  • 27
  • 117
  • 250

2 Answers2

1

If your object holds some kind of preference value, don't put it into a super-class. Make it static and/or use the singleton pattern and separate it from your application logic. This provides you with a more modular structure that will be easier to work with. The application class is probably overkill; singletons do the job most of the time. (The Android docs simply states: "There is normally no need to subclass Application.")

You can add it to a super-class, if it is a logical part of it though.

Don't forget to synchronize your object if it's going to be accessed by another/several thread(s).

Harry Silver
  • 397
  • 2
  • 11
1

There are different method to perform such requirement. Singleton is one of them. The other one is extending the application class. If you want a reference outlining all of these methods please see: What's the best way to share data between activities?

Community
  • 1
  • 1
Kasra
  • 3,045
  • 3
  • 17
  • 34