In Android how do you get an alert dialog to add an item to a list if the user presses yes and viceversa

StackOverflow https://stackoverflow.com/questions/7216846

  •  14-01-2021
  •  | 
  •  

Question

I am developing a simple Restaurant application in Android, I used menus and inflated submenu items corresponding to each menu item, I wanted to know a way of how to add the name of the dish to list only if the user selects yes in the alert dialog and viceversa. Here is my code

   public boolean onOptionsItemSelected(MenuItem m)
    {
        super.onOptionsItemSelected(m);
        switch(m.getItemId())
        {
            case R.id.Chicken_Biryani:
            selectedItem.add(m.getTitle().toString());
            cost.add(150);
            Toast.makeText(getApplicationContext(),"Hyderabadi special: Chicken   biryani costs 150 Rs"+selectedItem, Toast.LENGTH_LONG).show();
            showDialog(ALERT_DIALOG); 
            break;

            case R.id.Butter_Chicken:
            selectedItem.add(m.getTitle().toString());
            cost.add(150);
            Toast.makeText(getApplicationContext(),"Now with Punjabi Tadka: Butter Chicken costs 150 Rs", Toast.LENGTH_LONG).show();
            showDialog(ALERT_DIALOG);   

            break;

                   ........

      public Dialog onCreateDialog(int id) {
        switch(id)
        {
        case ALERT_DIALOG:
        AlertDialog.Builder ab = new AlertDialog.Builder(this);
        ab.setTitle("Buy Items");
        ab.setMessage(" You have added the item to your cart ");
        ab.setIcon(R.drawable.shopcart);
        ab.setPositiveButton("Ok", new DialogInterface.OnClickListener(){
            public void onClick(DialogInterface dialog, int which){         
            Toast.makeText(getApplicationContext(),"Item added to cart your cart contains "+selectedItem.size()+" Items", Toast.LENGTH_LONG).show();    
            }});    
    Dialog ad = ab.create();
        return ad;  
        }
        return null;    

        }

// how do i pass the data of the onOptionsItemSelected to the list only if the user selects yes in the alertdiaolog

Was it helpful?

Solution

Please see this question for more information. It links to another answer which talks about how and when you can use notifyDataSetChanged.

I think in your AlertDialog you would want an "Add" button and a "Cancel" button to cancel adding it to the cart. Upon clicking add, your would insert the item into the users cart. To add another button to your AlertDialog you would use ab.setNegativeButton(...) just as you did with the setPositiveButton. This is just my take on it, am I correctly understanding your use of onCreateDialog - or is it used only to tell the user it has been added?

Please see this question for more specific help on how to implement within an AlertDialog.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top