Time to post something. And that something will be about android development, since I started it some time ago. More about a work-around that I noticed when I was creating an app that had to use SQLite databases which was preloaded into memory for reading when the app started.
The database I used was rather large an I had to figure something out when the app was restarted for saving settings by pressing the back key on the phone and launching the app again.
While I was playing around, I noticed that when the back key was pressed, process would not get killed, but the application would close. So when you launch it again, objects would get newly created.
To stop this, I used what is called a “Singleton pattern” in OOP world. Wikipedia describes it as:
the singleton pattern is a design pattern that restricts the instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system
So because of it, you can only have one and the same object throughout your application. Very useful for settings and such.
It is very easy to implement in Java, here is an example of a Singleton class:
public class SingletonPatternExample { private static SingletonPatternExample example = null; private SingletonPatternExample() { // your code like normal goes in here } public static SingletonPatternExample getInstance() { if (example == null) { example = new SingletonPatternExample(); } return example; } // your code goes below }
And now in every other class that you want to use it, call the class like this:
exFromOtherClass = SingletonPatternExample.getInstance();
So if my application for launched first time, it would take some time to load the database, but when it would be closed and opened again, it would just use the object it created from the last time – this results in a much faster start.