0

I am now trying to add a dialog box after I clicked a button. When I click yes it should navigate to another page, if no it will stay on the page.

I tried to add the dialog box into the button but it gives me error. I am unsure about how I should proceed.

Please help.

MenuActivity.java

public class MenuActivity extends Activity {


private String server = "http://172.16.156.56";
private String sql_table = "orders";
private ListView list;
private String txtOrder, txtMember, txtPrice;
private Button btnAdd;
ArrayList<String> rows;

ListView listView1;
Button btnSubmit;
ArrayList<CustomItem> itemList, selectedList;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_menu);


    list=(ListView) findViewById(R.id.listView);
    btnAdd = (Button)findViewById(R.id.button);
    rows = new ArrayList<String>();


    itemList=new ArrayList<CustomItem>();
    itemList.add(new CustomItem("Fried Rice","description","1","Quantity"));
    itemList.add(new CustomItem("Fried Noodle","description","2","Quantity"));
    itemList.add(new CustomItem("Prawn noodle","description","3","Quantity"));
    itemList.add(new CustomItem("Chicken Rice","description","4","Quantity"));

    int[] prgmImages={R.drawable.friedrice,R.drawable.friednoodle,R.drawable.pnoodle,R.drawable.chickenrice};

    listView1 = (ListView) findViewById(R.id.listView);
    final CustomLVAdapter customLVAdapter = new CustomLVAdapter(this, itemList,prgmImages);
    listView1.setAdapter(customLVAdapter);

    Bundle extras = getIntent().getExtras();
    final String strMem = extras.getString("Mem");

    btnSubmit = (Button) findViewById(R.id.button);

    btnSubmit.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

         StringBuffer responseText = new StringBuffer();
            selectedList = new ArrayList<CustomItem>();
            int total = 0;
            for (int i = 0; i < itemList.size(); i++) {
                CustomItem object = itemList.get(i);
                if (object.isSelected()) {
                    responseText.append(object.getItem() + "," + object.getQty() + ",");//item
                    selectedList.add(object);
                    //calculate price
                    total = total + Integer.parseInt(object.getQty()) * Integer.parseInt(object.getPrice());

                }

            }
            txtOrder = responseText.toString();
            txtPrice = String.valueOf(total);

            Add(responseText.toString(), strMem, String.valueOf(total));

            Intent i = new Intent(v.getContext(), ReceiptActivity.class);
            i.putExtra("Order",txtOrder);
            i.putExtra("Price",txtPrice);
            i.putExtra("Mem",strMem);
            startActivity(i);

            Toast.makeText(getApplicationContext(), responseText + " $" + total,
                    Toast.LENGTH_SHORT).show();

            confirmdialog();

            SelectAll();
            //store in database

            //go to ReceiptActivity - membership, item, totalprice

        }

        private void confirmdialog() {

            AlertDialog.Builder alertDialog = new AlertDialog.Builder(MenuActivity.this);

            // Setting Dialog Title
            alertDialog.setTitle("Confirmation");

            // Setting Dialog Message
            alertDialog.setMessage("Submit order?");

       // Setting Positive "Yes" Button
            alertDialog.setPositiveButton("YES", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog,int which) {
                    //whatever you want to do
                    Intent i = new Intent(getApplicationContext(), ReceiptActivity.class);
                }
            });

            // Setting Negative "NO" Button
            alertDialog.setNegativeButton("NO", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    //cancel the dialog
                    dialog.cancel();
                }
            });

           alertDialog.show();
        }
    });


}

public void Add(final String item, final String membership, final String price)
{
    RequestQueue MyRequestQueue = Volley.newRequestQueue(this);
    String url = server + "/insertorder.php";
    StringRequest MyStringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {

        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
        }
    }) {
        protected Map<String, String> getParams() {
            Map<String, String> MyData = new HashMap<String, String>();
            MyData.put("item",item );
            MyData.put("membership",membership );
            MyData.put("price",price );

            return MyData;
        }
    };
    MyRequestQueue.add(MyStringRequest);
    SelectAll();
}
public void SelectAll()
{
    RequestQueue MyRequestQueue = Volley.newRequestQueue(this);
    String url = server + "/fetchorder.php";
    StringRequest MyStringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            try {
                JSONObject jsonResponse = new JSONObject(response);
                JSONArray jsonMainNode = jsonResponse.optJSONArray(sql_table);
                rows.clear();
                for(int i=0; i < jsonMainNode.length(); i++)
                {
                    JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
                    String order       = jsonChildNode.optString("item").toString();
                    String membership     = jsonChildNode.optString("membership").toString();
                    String price = jsonChildNode.optString("price").toString();

                    rows.add(order + ", " + membership + ", " + price );
                }
                ArrayAdapter<String> adapter = new ArrayAdapter<String>(MenuActivity.this,
                        android.R.layout.simple_list_item_1, rows);
                list.setAdapter(adapter);

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }, new Response.ErrorListener() { //Create an error listener to handle errors appropriately.
        @Override
        public void onErrorResponse(VolleyError error) {
            //This code is executed if there is an error.
        }
    });
    MyRequestQueue.add(MyStringRequest);
}

}

Logcat

 07-07 16:43:37.425 8696-9039/com.example.android.cardemulation E/AndroidRuntime_3_crash: crash in the same process: Thread-2418
java.lang.OutOfMemoryError: Failed to allocate a 493188205 byte allocation with 16777104 free bytes and 142MB until OOM
at com.android.volley.toolbox.DiskBasedCache.streamToBytes(DiskBasedCache.java:316)
at com.android.volley.toolbox.DiskBasedCache.readString(DiskBasedCache.java:526)
at com.android.volley.toolbox.DiskBasedCache.readStringStringMap(DiskBasedCache.java:549)
at com.android.volley.toolbox.DiskBasedCache$CacheHeader.readHeader(DiskBasedCache.java:392)
at com.android.volley.toolbox.DiskBasedCache.initialize(DiskBasedCache.java:155)
at com.android.volley.CacheDispatcher.run(CacheDispatcher.java:84)
07-07 16:43:37.478 8696-8696/com.example.android.cardemulation E/WindowManager: android.view.WindowLeaked: Activity com.example.android.cardemulation.MenuActivity has leaked window com.android.internal.policy.PhoneWindow$DecorView{7727bec V.E...... R....... 0,0-1026,543} that was originally added here
at android.view.ViewRootImpl.<init>(ViewRootImpl.java:397)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:299)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:85)
at android.app.Dialog.show(Dialog.java:319)
at android.app.AlertDialog$Builder.show(AlertDialog.java:1112)
at com.example.android.cardemulation.MenuActivity$1.confirmdialog(MenuActivity.java:154)
at com.example.android.cardemulation.MenuActivity$1.onClick(MenuActivity.java:116)
at android.view.View.performClick(View.java:5226)
at android.view.View$PerformClick.run(View.java:21266)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:168)
at android.app.ActivityThread.main(ActivityThread.java:5845)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:797)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:687)
Hitesh Sahu
  • 41,955
  • 17
  • 205
  • 154
goh
  • 5
  • 9
  • If you want to start intent in the positive case, why your startActivity(i) is before your confirmDialog()? – Erik Minarini Jul 07 '16 at 08:53
  • use small sized images, I guess you're using large images and the program is crashing with out of memory exception – SripadRaj Jul 07 '16 at 09:03
  • tried putting confirmdialog before startactivity, still getting the same error @ErikMinarini – goh Jul 07 '16 at 09:03
  • Before i added the dialog codes the app was able to run without problems. @SripadRaj – goh Jul 07 '16 at 09:06
  • What is there on `MenuActivity.java:154`? –  Jul 07 '16 at 09:16
  • dialog.cancel @nerdyGeek – goh Jul 07 '16 at 09:20
  • Does the app crash when you click on the cancel button on the dialog (or on any other event), or does it crash as soon as you launch the app? –  Jul 07 '16 at 09:22
  • it crashes after i clicked the button @nerdyGeek – goh Jul 07 '16 at 09:47
  • What happens if you say `dialog.dismiss()` instead of `dialog.cancel()`? –  Jul 07 '16 at 10:03
  • Hi, this question was closed, so I cannot post an answer. However, your problem is that you are calling `confirmdialog();` _after_ calling `startActivity(i)`. You cannot show a dialog outside of an activity context. In your case, your original activity has already exited (since you called `startActivity`) before you show the dialog. Try putting `startActivity(i)` inside `setPositiveButton`'s `onClick()`. – Ishita Sinha Jul 07 '16 at 10:14
  • it still has the same error @nerdyGeek – goh Jul 08 '16 at 01:07
  • Just tried it still has the same error @IshitaSinha – goh Jul 08 '16 at 01:07
  • See if this helps: http://stackoverflow.com/questions/5297687/android-startactivity-from-alertdialog – Ishita Sinha Jul 08 '16 at 04:04
  • @IshitaSinha's link might help as well as these two: http://stackoverflow.com/questions/7725582/how-to-start-activity-only-after-user-clicks-ok-on-alertdialog and http://stackoverflow.com/questions/6462087/how-to-launch-an-activity-from-a-dialog –  Jul 08 '16 at 04:07

0 Answers0