9

I have an alert that I want to display only the first time right after starting the application for the first time.

How can I do that?

Octavian A. Damiean
  • 39,079
  • 19
  • 94
  • 100
waa1990
  • 2,275
  • 9
  • 26
  • 31

1 Answers1

23

There are a few ways to do this, but perhaps the easiest is just to check a flag in a SharedPreferences object and set it once the alert is shown.

SharedPreferences

Something like

public class MyActivity extends Activity {

public static final String PREFS_NAME = "MyPrefsFile";

@Override
protected void onCreate(Bundle state){

   super.onCreate(state);
   SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
   boolean dialogShown = settings.getBoolean("dialogShown", false);

   if (!dialogShown) {
     // AlertDialog code here

     SharedPreferences.Editor editor = settings.edit();
     editor.putBoolean("dialogShown", true);
     editor.commit();    
   }
}
Brian Cooley
  • 11,480
  • 4
  • 39
  • 39