Search code examples
androidandroid-fragmentsandroid-activityandroid-dialogfragment

How to show a dialog in android on navigating to another activity for the first time?


How to show a dialog in android on navigating to another activity only for the first time? I dont want to put it in the onResume() of the activity because then the dialog shows up each and every time i navigate to that activity.


Solution

  • Use this finction in onCreate handler

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ...
        if (isFirstTime()) {
            // show dialog
        }
        ...
    }
    
    
    /***
     * Checks that application runs first time and write flag at SharedPreferences 
     * @return true if 1st time
     */
    private boolean isFirstTime()
    {
        SharedPreferences preferences = getPreferences(MODE_PRIVATE);
        boolean ranBefore = preferences.getBoolean("RanBefore", false);
        if (!ranBefore) {
            // first time
            SharedPreferences.Editor editor = preferences.edit();
            editor.putBoolean("RanBefore", true);
            editor.commit();
        }
        return !ranBefore;
    }