A singleton that keeps a Context reference, without care for what type of context it is, can easily cause an Android Context (typically, Activity) leak.

Consider this:

- First singleton access is from Activity "A", which passes "this" as a Context into the singleton's constructor.

- The singleton instance is created, keeping the Context reference that was passed in.

- Activity "A" goes away, Activity "B" also calls Singleton.get(this).

--- time passes ---

- Activity "A" is long gone from the screen, paused, possibly had finish() / onDestroy called.

- Activity "B", which is now on the screen, has a reference to the singleton, which has a reference to Activity "A" (as a Context).

-->> Activity "A" is long unneeded, but cannot be GC'd.

One way to fix this, that I and many others posted here, is for the singleton initializer to call getApplicationContext() on the Context that's passed in, and keep a reference to the return value, rather than the original Context.

-- Kostya

23.02.2011 14:16, Indicator Veritatis пишет:
Why would a singleton cause a memory leak? Once the reference returned
by getInstance() is no longer used, it is subject to garbage
collection. And when there are no more references to the singleton
itself, it too is subject to garbage collection. So no memory leak.

On Feb 22, 8:39 am, ydm<jordanmiladi...@gmail.com>  wrote:
Thank you, Kostya, but I'm not sure a singleton, which holds a
reference to the first activity's context, wouldn't cause memory
leaks. The best solution I found so far is to use the Application
object as context for the database object.

On Feb 22, 12:46 pm, Kostya Vasilyev<kmans...@gmail.com>  wrote:







22.02.2011 13:32, ydm пишет:
I'm curious why the SQLite db requires a Context object,
The database class doesn't - SQLiteOpenHelper (subclass) does, to get
the location of the database file.
and what I
should do to share the same instance of a db object between many
activities? Should I initialize it in the first activity and use it
across the application, or may be any activity should reinitialize the
db with itself as db context?
If you're not going to implement a private content provider (which is
one way), I'd use a simple singleton, keeping a reference to one and
only SQLiteOpenHelper subclass object, initialized with the application
context.
-- Kostya
--
Kostya Vasilyev --http://kmansoft.wordpress.com


--
Kostya Vasilyev -- http://kmansoft.wordpress.com

--
You received this message because you are subscribed to the Google
Groups "Android Developers" group.
To post to this group, send email to android-developers@googlegroups.com
To unsubscribe from this group, send email to
android-developers+unsubscr...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/android-developers?hl=en

Reply via email to