tags:

views:

141

answers:

3

Hi All!

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 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
fredley
A: 

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.

Sameer Segal
+1  A: 

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
}
vmlinuz
Hello vmlinuz thanks so much for you answer, I really got a good brief idea regardiing what I should do next. Just had one doubt:- " Can you please tell me what exactly ("MyApp", 0) in the very first line means? Thanks,david
david
David (or John?), "MyApp" is an arbitrary filename - you can have more than one preferences file for an app, and the file can be used by more than one part of the app at once, so the filename is an identifier. The 0 is a mode for the file, and you probably just want to leave it at 0...
vmlinuz
Thanks for the explanation vmlinuz
david