Skip to content
Advertisement

Android – Using Shared Preferences in separate class?

I want to save data using Shared Preferences in android. But I am looking to use separate class to do this task. I have implemented that class like below,

JavaScript

But there is an error on getActivity(),

JavaScript

How to solve this?
Thanks

Advertisement

Answer

getActivity() is a method of Fragment not of your SavePref. In your case the simple fix is to use the Context you are keeping as member variable to retrieve the SharedPreferences. An alternative to your approach is to avoid keeping the context as member variable, linking somehow the shared preferences to an instance of of your SavePref class, and have a static method

JavaScript

and address the method like:

JavaScript

from a Fragment or

JavaScript

from an Activity. This way you don’t need to instantiate SavePref every time you need to call saveInt, and you can avoid to store a reference to the Context.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement