javaandroidandroid-alertdialog

Display Logout with an alert dialog inside a toolbar


[Need help. How can I perform logout with alert dialog inside a toolbar?Because I want an alert dialog to be shown when user wanted to logout to his account. I'm in the stage of learning. Hope you can help me guys hehe. Here isd the code for my logout activity: : ][1] [2]

  [1]: https://i.sstatic.net/lU7i1.png




   @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            getMenuInflater().inflate(R.menu.menu, menu);
            return super.onCreateOptionsMenu(menu);
        }

        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            int id = item.getItemId();
            AlertDialog.Builder alert = new AlertDialog.Builder(MainActivity.this);
            alert.setMessage("Are you sure?")
                    .setPositiveButton("Logout", new DialogInterface.OnClickListener() {

                        public void onClick(DialogInterface dialog, int which) {

                        }
                    }).setNegativeButton("Cancel", null);

            AlertDialog alert1 = alert.create();
            alert1.show();
            if (id == R.id.action_settings) {
                logout();
                return true;
            }
            return super.onOptionsItemSelected(item);
        }

        private void logout() {
            startActivity(new Intent(this, LoginActivity.class));
            finish();
        }

Solution

  • You need to think algorithm structure.

    First, user clicks options menu and select logout.

    Then, show popup.

    Lastly, user interacts with this popup and validate logout.

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            // This is first step.
            showPopup(); 
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
    
    // first step helper function
    private void showPopup() {
        AlertDialog.Builder alert = new AlertDialog.Builder(MainActivity.this);
        alert.setMessage("Are you sure?")
                .setPositiveButton("Logout", new DialogInterface.OnClickListener()                 {
    
                    public void onClick(DialogInterface dialog, int which) {
    
                        logout(); // Last step. Logout function
    
                    }
                }).setNegativeButton("Cancel", null);
    
        AlertDialog alert1 = alert.create();
        alert1.show();
    }
    
    private void logout() {
        startActivity(new Intent(this, LoginActivity.class));
        finish();
    }