0

I allocate this database queries object in several activities and fragments these are heavy static databases contains hundreds of thousands of records.

if I allocate and deallocate these objects this may incur heap fragmentation.does android automatically closes connection when context in which db connection opened is no longer exists even if I am not using context object while opening database connection.

public DatabaseQueries() 
    {
        dbForUpdationList = SQLiteDatabase.openDatabase(
                Environment.getDataDirectory()+"/data/package/databases/updation_list.db", null,
                SQLiteDatabase.OPEN_READONLY);
        dbForVillageWadiList = SQLiteDatabase.openDatabase(
                Environment.getDataDirectory()+"/data/package/databases/village_wadi.db", null,
                SQLiteDatabase.OPEN_READONLY);          

    }
James Z
  • 12,209
  • 10
  • 24
  • 44
raju
  • 53
  • 6

1 Answers1

1

Memory leak in Java is a situation where some objects are not used by the application any more, but Garbage Collection fails to recognize them as unused and so, does not clean it up.

Every time you create an object, some space in memory is reserved for that object. And the same is for any Database Connection. So, after using the connection, if you dont close it, the GC doesnt get to know that this object will not be used anymore and hence does not delete it. So, it stays there in memory, eating valuable resource while the rest of the program runs. [Hence resource leak].

This is not at all desired. Furthermore, this exposes your program to security issues, as the connection is open, it is vulnerable, and changes can be made to the database. Remember, Even after the Activity closes, if there is a running thread, or an AsyncTask, the database connection remains open as well along with the thread.

Further reading : What is a memory leak? StackOverflow : Closing database connection to avoid memory leak

Community
  • 1
  • 1
Samrat Dutta
  • 1,727
  • 1
  • 11
  • 23