Posted by
sapan
on
- Get link
- Other Apps
1. getSharedPreferences()
— Use this if you need multiple shared preference files identified by name, which you specify with the first parameter. You can call this from any Context
in your app. Context context = getActivity(); SharedPreferences sharedPref = context.getSharedPreferences( getString(resource id), Context.MODE_PRIVATE);Note : getString method can be accessed from the Context object , it take resource as parameter
2. getPreferences()
— Use this from an Activity
if you need to use only one shared preference file for the activity. Because this retrieves a default shared preference file that belongs to the activity, you don't need to supply a name.SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor
by calling edit()
on your SharedPreferences
. Pass the keys and values you want to write with methods such as putInt()
and putString()
. Then call commit()
to save the changes.SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE); SharedPreferences.Editor editor = sharedPref.edit(); editor.putInt(getString(“YourKEY”, “MY VALUE”); editor.commit();
getInt()
and getString()
, providing the key for the value you want, and optionally a default value to return if the key isn't present.SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE); long highScore = sharedPref.getInt(getString(“MyKEY”, “Default Value if no value is found”);
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE); SharedPreferences.Editor editor = sharedPref.edit(); editor.remove("MYKEY"); editor.commit();
Comments
Post a Comment