SharedPreference example in Android
Application shared preferences allows you to save and retrieve data in key, value pair.
Initialization of SharedPreference in Android:.
Application shared preferences can be fetched using getSharedPreferences() method.The following code can be used to get application shared preferences.
SharedPreferences
pref = getApplicationContext().getSharedPreferences(
"any_prefname", MODE_PRIVATE);
Available mode
for shared preference:
Editor editor =
pref.edit();
and to save data
commit() is used.
Editor.commit();
You can save data
into shared preferences using editor. All the primitive data types
like booleans, floats, ints, longs, and strings are supported. Call
editor.commit() in
order to save changes to shared preferences.
editor.putBoolean("key_name", true); // Storing boolean
- true/false
editor.putString("key_name", "string
value"); // Storing string
editor.putInt("key_name", "int
value"); // Storing integer
editor.putFloat("key_name", "float
value"); // Storing float
editor.putLong("key_name", "long
value"); // Storing long
editor.commit();
// commit changes
Get data from
Shared Preference:
Data can be
retrived from saved preferences by calling getString()
(For string) method.for boolean getBoolean() Remember this method
should be called on Shared Preferences not on Editor.
// returns stored
preference value
// If value is
not present return second param value - In this case null
pref.getString("key_name", null); // getting String
pref.getInt("key_name", null); // getting Integer
pref.getFloat("key_name", null); // getting Float
pref.getLong("key_name", null); // getting Long
pref.getBoolean("key_name", null); //
getting boolean
Delete data from
shared preference and delete sharedpreference:
To delete data
from shared preferences we can use
remove(“key_name”).If
we want to delete all the data, call
clear()editor.remove("student_name");//will delete student_ name editor.commit();
|
editor.clear(); editor.commit();
|
Our new android application for EGreeting.Have a look to it.
The Greetings Android Application
NovaRadix Android Application Development Team NovaRadix Technology WWW.NOVARADIX.COM
Can I set sharedpreference in a custom view and get in an activity?? If yes how?
ReplyDeleteGood work.............also get a detail tutorial with sample project at......http://androidtutorialsrkt.blogspot.in/
ReplyDeleteThanks for the help would you guys be so kind to play and rate this game -- -- -- -- --|> "Tap n Flap"
ReplyDeletehttps://play.google.com/store/apps/details?id=com.rainydaygames.tapnflap.android&hl=en
if you are new in android so visit here for good android tutorial with examples..
ReplyDeletehttp://androidexample.com/