I need a suggestions how to achieve something in android and Java. I have a big project which has more than 50 activities and I use two different database classes to query sqlite statements and retrieve information from my system and user database. Here is an example how I am using and initializing my database :
SystemDatabaseHelper dbHelper = new SystemDatabaseHelper(this, null, 1);
dbHelper.initialize(this);
I am doing that in activity and the last few days I read a lot for memory leaks in android and the whole information about giving Context to a non-activity classes and the leaks which this can cause. My question is which is the best way to create some class and initialize it only from main activity and than use it in all other activities without initializing it again and again.
Any suggestions which is the best way to achieve this…i have some ideas,but want to hear your suggestions and best practices.
if you are trying to initialize your database helper class only once you’re looking for singleton right?? here is an example how you can make it
if you call
ContactDBHelper.getInstance();the first time , it will initialize the instance , after that any application component or any method will call it , it wont initialize it will return the singleton initialized instance .note : for the Util.getApplicationContext it is a static helper method that returns application context which is set in the main Activity .
for memory leaks , you can avoid or protect your app from it using
WeakReferenceorSoftRerferencehere is the Util class