I suggest creating a model class (let's call it MyModel
) and creating object of this class in Application.onCreate
(not Activity.onCreate
).
After that adding getter for that, so you can get this model from any Activity
or Service
like this:
MyApplication app = (MyApplication) getApplication();
MyModel model = app.getMyModel();
User user = model.getCurrentUser();
etc.
Also creating BaseActivity
class can save you typing if you create method there protected MyModel getModel()
which returns model from the first 2 lines of the code above.
Edit:
You need to create a class that extends Application
and register this class in AndroidManifest.xml
.
This is how: https://stackoverflow.com/a/2929927/2183804
Edit (about singleton):
It is said to be an anti-pattern (not only on Android). In Android I have seen people ending with singleton with accessor like MySingleton.getInstance(Context), because they needed Context anyway, e.g. for SharedPrefs or DB access. This is what Application is for, so there is no need to create additional, hackish entity, which could be used in a wrong way: MySingleton.getInstance(null) from a place where there is no Context available. This could lead to NPE after process is killed and restarted.