Java – Static access to common functions?

Static access to common functions?… here is a solution to the problem.

Static access to common functions?

I

have a question that may be more general, but I ran into it during android development :

How can I best share my usual methods?
For example, retrieving shared preferences by key is always the same code. But if I have to use it in a different fragment or activity, 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();
}

Is it good practice to make it public static in the GlobalUtils class?
How will you handle these features?

Solution

You can definitely create a static class, such as GlobalUtils, or even a dedicated class for SharedPreferences. You simply pass Context to the method so that you can get the SharedPreferences object. You can do it according to your needs; I’ve taken these classes countless times. I even have a thread-safe SharedPreferences wrapper 🙂

EDIT: Looking at my code again, half of my SharedPreference wrapper is static and the rest is lazy instantiated. That being said, I think you should do whatever you feel comfortable with, as long as the rest of your code doesn’t need to be done either way.

Related Problems and Solutions