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,
import android.content.Context; import android.content.SharedPreferences; public class SavePref { private Context context; public SavePref(Context context){ this.context = context; } public void saveInt(String key, int value) { SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE); SharedPreferences.Editor editor = sharedPref.edit(); editor.putInt(key, value); editor.commit(); } }
But there is an error on getActivity()
,
The method getActivity() is undefined for the type SavePref
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
public static void saveInt(Context context, String key, int value) { SharedPreferences sharedPref = context.getDefaultSharedPreferences(Context.MODE_PRIVATE); SharedPreferences.Editor editor = sharedPref.edit(); editor.putInt(key, value); editor.commit(); }
and address the method like:
SavePref.saveInt(getActivity(), key, value);
from a Fragment
or
SavePref.saveInt(this, key, value);
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
.