What is SharedPreferences in Android?
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
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 only want to create your dialog box once when the application is installed you can use the following along with the code above. This will be set for the first time and all subsequent times will not be loaded.
/* Loading default preferences the first time application is run */
PreferenceManager.setDefaultValues(getApplicationContext(),
R.xml.preference, false);
You can set a bool value in your preference.xml and make it false in onCreate(), so as to never repeat the AlertDialog again.
精彩评论