I have a question which might be more general, but I came across it during android dev:
How can I best share own common used methods?
Eg retrieving a shared preference by key is always the same code. But if I have to use it in different Fragments or Activities, I always have to copy the same code:
private void setSharedPrefs(String key, String value) {
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = settings.edit();
editor.putString(key, value).commit();
}
It it a good habit to make this a public static in a GlobalUtils class or so?
How would you handle these kind of functions?
Yes you could make it public static:
Be careful in some situations where you may hold onto the context after an activity has died, that is bad.
A more likely scenario your describing could be to create a class like this:
You would lazy init this class in your class that extends Application and have a getter in there to retrieve it, with something like:
and use it like so:
EDIT
Example of Lazy initialisation:
N.B This is lazy initialization within a class that extends
Applicationthereforethisrefers to your application context and will live for the duration of your Application. If you where using an Activity context you would not want to use lazy initialisation. (So use the application context!)