1

I'm creating a singleton class that is static as it needs to be accessed from everywhere. This class needs to write to shared preferences often. To create Shared references object, I will need context.

I read that it is bad idea to store a reference to Context in a static class as the context can't garbage collected especially if it was activity.

Therefore, I created methods that wherever it needs to write to share preferences, I pass in context. This is resulting in creating shared preferences object, storing data, then deleting the object.

Is this ok? Why or why not?

Thank you

mixel
  • 25,177
  • 13
  • 126
  • 165
Snake
  • 14,228
  • 27
  • 117
  • 250

2 Answers2

4

Your can simply

SharedPreferences pref = PreferenceManager.
       getDefaultSharedPreferences(context.getApplicationContext());

So whenever context is finalized you won't care because you use application context

0
public ClassSingle{

       private static ClassSingle classSingle = null;

        public ClassSingle(Context context) {
          //default values of variable if any
        }

       synchronized public static ClassSingle getInstance(Context context) {
           if (classSingle == null) {
               String configJson = context.getSharedPreferences(ApplicationConstants.PREF_FILE_CONFIG, Context.MODE_PRIVATE)
                .getString(ApplicationConstants.EXTRA_KEY, null);
              try {
                  classSingle = new Gson().fromJson(configJson, ClassSingle.class);
              } catch (JsonSyntaxException e) {
                  e.getStackTrace();
              }

              if (classSingle == null) {
                 classSingle = new ClassSingle(context);
         }
      }
      return classSingle;
     }
}

Use this way to make class singlton and to get instance everywhere.. It will create new instance if it not there, otherwise it will return existing instance.

Ankit Kumar
  • 3,663
  • 2
  • 26
  • 38