6

When the user clicks on the save button, an AlertDialog appears and asks the user to input text for the file name.

If the user clicks the positive button ("Ok") without specifying a name, I want to display a toast which asks them to do so, and keep the AlertDialog open. But the toast never displays and the dialog closes.

The code for the AlertDialog is here:

    AlertDialog.Builder alert = new AlertDialog.Builder(this);

    alert.setTitle(R.string.save_game);
    alert.setMessage(R.string.request_name);

    // Set an EditText view to get user input 
    final EditText input = new EditText(this);
    input.setHint(R.string.untitled);
    alert.setView(input);

    alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int whichButton) {
      String value = input.getText().toString();
      if(value != null){
          // Do something with value      
      }
      else{
          Toast.makeText(context, R.string.no_name_given, Toast.LENGTH_SHORT).show();
      }
    }
    });

    alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int whichButton) {
        // Canceled.
    }
    });

    alert.show();

How can I make this happen?

Thanks!

Rookatu
  • 1,487
  • 3
  • 21
  • 50

6 Answers6

6
Public void showToast() {
    Toast.makeText(this, R.string.no_name_given, Toast.LENGTH_SHORT).show();
} 

Just call this method instead of displaying toast from an alert dialog box like this in your code.

else {
    showToast();
}

To keep it open use this method

public void forceOpen() {

    AlertDialog.Builder alert = new AlertDialog.Builder(this);

    alert.setTitle(R.string.save_game);
    alert.setMessage(R.string.request_name);

    // Set an EditText view to get user input 
    final EditText input = new EditText(this);
    input.setHint(R.string.untitled);
    alert.setView(input);

    alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int whichButton) {
            String value = input.getText().toString();
            if(value != null) {
                // Do something with value      
            }
            else {
                Toast.makeText(context, R.string.no_name_given, Toast.LENGTH_SHORT).show();
            }
        }
    });

    alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int whichButton) {
            // Canceled.
        }
    });

    alert.show();

}

Just reopen it.. Not sure why it closes but this will work

Nipun
  • 990
  • 1
  • 16
  • 25
NightSkyCode
  • 1,141
  • 2
  • 16
  • 33
  • This displayed the Toast, but did not keep the `AlertDialog` open. – Rookatu Aug 02 '13 at 06:21
  • Hmm not sure why, you never called close. Just reopen it when the user clicks OK.. They won't notice – NightSkyCode Aug 02 '13 at 06:28
  • I see you put the code into a method. You are suggesting that the method calls itself from within the code for the click on "Ok", in a kind of recursion? The thing is, I don't think that the first `AlertDialog` is destroyed until the click is consumed, so this would likely layer `AlertDialog` on top of `AlertDialog` – Rookatu Aug 02 '13 at 06:37
  • Yes make it a method and have it call itself. And no, I just tried it and it looked natural. There is no other way to do this without creating a custom dialog box from scratch without its own layout – NightSkyCode Aug 02 '13 at 06:41
  • Okay, I tried it and it works. It seems hacky, but if the only other option is to make a custom dialog I'll take this for now. Thanks! – Rookatu Aug 02 '13 at 06:45
  • Yes it is hacky but if hacky works there's nothing wrong with that. And no problem! – NightSkyCode Aug 02 '13 at 06:47
2

Change the code as follows:

if(value != null && value.length()>0){

// Do something with value      
 }else{
          Toast.makeText(context, R.string.no_name_given, Toast.LENGTH_SHORT).show();
}
Suji
  • 6,044
  • 2
  • 19
  • 17
  • This displayed the Toast, but did not keep the `AlertDialog` open. – Rookatu Aug 02 '13 at 06:21
  • @Rookatu, did you try the above solution? Hope it would work as your previous if condition was not checking the length of text value. – Suji Aug 02 '13 at 06:22
  • Yes, I tried your suggestion. It fixed the issue about the Toast not displaying, but as my above comment stated, it did not keep the `AlertDialog` open. I want to keep it open until the user either inputs a valid file name and presses "Ok", or presses "Cancel". – Rookatu Aug 02 '13 at 06:24
  • AlertDialog will be closed by default when you click on any provided button rt? If you still want to have it, go for custom dialog (dialog with custom layout xml) as shown here: http://stackoverflow.com/questions/4016313/how-to-keep-an-alertdialog-open-after-button-onclick-is-fired – Suji Aug 02 '13 at 06:28
1

You can disable the Ok button.If the condition is validate,then enable button again.

G-zone
  • 21
  • 1
  • 3
0
public void alert()
    {
        LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View v = inflater.inflate(R.layout.simple, null);

        final EditText etText = (EditText) v.findViewById(R.id.etName);

        final AlertDialog d = new AlertDialog.Builder(this)
        .setView(v)
        .setTitle("Warning ..")
        .setPositiveButton(android.R.string.ok,
                new Dialog.OnClickListener() {
            @Override
            public void onClick(DialogInterface d, int which) 
            {
                //Do nothing here. We override the onclick
                Toast.makeText(getApplicationContext(), "Enter Text", Toast.LENGTH_LONG).show(); 
            }
        })
        .setNegativeButton(android.R.string.cancel, null)
        .create();
        d.show();
}
Sanket Shah
  • 4,352
  • 3
  • 21
  • 41
0

A simple way what worked for me to get Context from AlertDialog's OnClick method using DialogInterface:

((Dialog) dialogInterface).getContext()

Using it in OnClick() method:

public void onClick(DialogInterface dialogInterface, int which) {
        Toast.makeText(((Dialog) dialogInterface).getContext(), "Bla-bla" , Toast.LENGTH_SHORT).show();
}
Abigail La'Fay
  • 749
  • 1
  • 9
  • 18
0

General Solution

If you want to update anything on Activity from a Dialog this solution might help. For example, showing a toast message from a Dialog button click.

Create a listener

public interface YesNoClickListner {

    public void yesClicked();

    public void noClicked();
}

Pass the interface in your dialog

public class FireMissilesDialog extends DialogFragment {

    private YesNoClickListner listner;

    public FireMissilesDialog(YesNoClickListner listner){
        this.listner = listner;
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {

        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setMessage("This is custom Dialog")
            .setPositiveButton("YES", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    listner.yesClicked();
                }
            })
            .setNegativeButton("NO", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    listner.noClicked();
                }
            });
        return builder.create();
    }
}

Implement the listener in your Activity and override methods

public class MainActivity extends AppCompatActivity implements YesNoClickListner{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        FireMissilesDialog fireMissilesDialog = new FireMissilesDialog(this);
        fireMissilesDialog.show(getSupportFragmentManager(),"Dialog");

    }

    @Override
    public void yesClicked() {
        Toast.makeText(this, "Yes Clicked", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void noClicked() {
        Toast.makeText(this, "No Clicked", Toast.LENGTH_SHORT).show();
    }
}

Result:

enter image description here

This solution may not be exactly what you need to solve this particular question. But this works in general. For example, if you need to update a textView in your Activity on YES button click then just override method this like.

@Override
public void yesClicked() {
   Toast.makeText(this, "Yes Clicked", Toast.LENGTH_SHORT).show();
}

Relevant Link:

Full working code

Rohit Singh
  • 16,950
  • 7
  • 90
  • 88