SharedPreferences class allows you to save and retrieve primitive data types in key-value pairs. The data saved using SharedPreferences will be available even after your application is killed. This capability makes SharedPreferences suitable in different situations when user settings needs to be saved for example, or store data that can be used in different activities.
The data types that can be saved are booleans, floats, ints, longs, and strings.
To get an instance of SharedPreferences use the getSharedPreferences(String, int) method. The method takes 2 parameters: the name of the preference settings and the mode. (0 or MODE_PRIVATE for the default operation, MODE_WORLD_READABLE and MODE_WORLD_WRITEABLE to control permissions)
To write values:
- Call edit() to get a SharedPreferences.Editor instance
- Add values with methods such as putInt() and putString().
- Call commit() to save values.
To read values use such methods as getString() and getInt() of SharedPreferences instance.
Here’s a simple usage of SharedPreferences class:
public class SharedPrefsActivity extends Activity { public static final String PREFS_NAME = "MyApp_Settings"; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); SharedPreferences settings = getSharedPreferences(PREFS_NAME, MODE_PRIVATE); // Writing data to SharedPreferences Editor editor = settings.edit(); editor.putString("key", "some value"); editor.commit(); // Reading from SharedPreferences String value = settings.getString("key", ""); Log.d(TAG, value); } }
Hmmm… Nice Blog.. Keep it up π
Hey :),
Nice Blog!! π
Thanks, feel free to get the most of it. π
can we use put string + commit first and then in the last of the programcan we use get string+commit?
I want to access stored value in shared preferences in a fragment. How can i do this? As it is a class extending Fragment and not activity. It gives me error..
use “getActivity()” to access shared preferences.
eg.:
i want to print shared preferences value in emulater ,so what me do?
You can add a TextView to your layout and set the shared prefs value to the TextView, or display it in logs, like in the example above.
hi nice blog
hi i don’t know how to create the sqlite data base example for login and signup page
Hi thanks for your sharing,
I would like to know how can we retrieve our datas in Shared Preferences if we are using different classes?
Thanks
Best Regards
M Idham Habibie