0

I want to display alertDialog only once. The first time user clicks on the play button, alertDialog should appear. User can stop the game. If he wishes to play again,the alertDialog should not appear again.

I've tried using sharedPreferences, but alertDialog is never displayed.

    public boolean added = false;

 private void startRoute(MenuItem item) {

            SharedPreferences prefs = getContext().getSharedPreferences("myPref",Context.MODE_PRIVATE);
            boolean added = prefs.getBoolean("added",false);
            if(!added)
            {
                addRouteToCal();
            }
            refreshProgress();
    }

 private void addRouteToCal() {

        final EditText taskEditText = new EditText(getContext());

        new AlertDialog.Builder(getContext())
                .setTitle(getString(R.string.current_add_to_favorites))
                .setMessage(getString(R.string.current_name_favorites))
                .setView(taskEditText)
                .setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        String name=String.valueOf(taskEditText.getText());
                        saveRouteDone(name);
                        SharedPreferences.Editor prefs = getContext().getSharedPreferences("myPref",Context.MODE_PRIVATE).edit();
                        prefs.putBoolean("added",true);
                        prefs.commit();
                    }
                })
                .setNegativeButton(getString(R.string.cancel), (dialog, which) -> {
                })
                .show();
        ;

Any idea of what I did wrong ?

David
  • 221
  • 3
  • 13
  • Where is the code which sets the `added` boolean field on the class? – Deepak Khillare Oct 15 '19 at 09:49
  • Sorry, deleted it without paying attention. Updated my code ! @DeepakKhillare – David Oct 15 '19 at 09:52
  • The `public boolean added=true` is not needed and is adding to the confusion. Also, there might be two different context because of which the preference value is not what you're expecting. Read more about context https://stackoverflow.com/questions/10641144/difference-between-getcontext-getapplicationcontext-getbasecontext-and. You might want to use singleton class for storing/retrieving app preferences. – Deepak Khillare Oct 15 '19 at 10:05
  • Yes ok it did help deleting the variable declaration, but now if I want to start a new game, the alertDialog is not shown. Every time a new game is started, I'd like to show the alertDialog, what do I have to change ? – David Oct 15 '19 at 10:10

0 Answers0