Can anybody please clear me about the SharedPreferences in Android. How can I set a condition of displaying a "Alert Message" only once when the Activity gets loaded initially in the Application?
How it is done by using SharedPreferences?
Thsnks, John
A SharedPreferences object points to a file containing key-value pairs and provides simple methods to read and write them. Each SharedPreferences file is managed by the framework and can be private or shared. This page shows you how to use the SharedPreferences APIs to store and retrieve simple values.
Shared Preferences allow you to save and retrieve data in the form of key,value pair. In order to use shared preferences, you have to call a method getSharedPreferences() that returns a SharedPreference instance pointing to the file that contains the values of preferences.
Android Shared Preferences Overview Android stores Shared Preferences settings as XML file in shared_prefs folder under DATA/data/{application package} directory. The DATA folder can be obtained by calling Environment.
SharedPreferences are used in android to store some data presistently(i.e. after closing of application, it will persist). If you want to store few amount of data then you can go for SharedPreferences rather than going for Sqlite and all.In that case SharedPreferences are useful.
It's completely by coincidence, I swear, that I blogged about this today :)
SharedPreferences settings = this.getSharedPreferences("MyApp",0);
boolean firstrun=settings.getBoolean("firstrun",true);
if (firstrun) {
SharedPreferences.Editor e = settings.edit();
e.putBoolean("firstrun",false);
e.commit();
// Do something here that you only want to happen the first time
}
SharedPreferences sp = context.getSharedPreferences("myApp",0);
boolean showAlert = sp.getBoolean("Alert",true); //defaults to true if no value set
//Show alert if true
sp.setBoolean("Alert",false); //set to false
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With