Home > Software engineering >  Logout from Navigation Drawer
Logout from Navigation Drawer

Time:01-04

I would like to create a logout alert dialog from my applications navigation drawer. All the other items in the nav drawer are fragments and I would like for this item to just show an alert dialog

Navigation Drawer

I previously had a button in my MainActivity that used an on click listener and firebase.getInstance.signOut() to take the user back to the login activity:

Previous button on click listener

 //on click listener for logout
    /*btnLogout.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            FirebaseAuth.getInstance().signOut();
            startActivity(new Intent(getApplicationContext(),LoginActivity.class));
            finish();
        }
    });*/

After some redesign I created a navigation drawer that utilizes fragments and i would like when the user selects logout to be prompted with an alert dialog asking are they sure , then for the button to act just how my previous one did and send the user back to the login activity.

I dont see the need of creating another fragment to logout but, correct me if I'm wrong.

Mainactivity.java

public class MainActivity extends AppCompatActivity implements NavigationView.
    OnNavigationItemSelectedListener,MainFragment.onFragmentBtnSelected{


public TextView verifyMsg;
public Button btnLogout, verifyEmailBtn;
FirebaseAuth fauth;
public DrawerLayout drawerLayout;
public ActionBarDrawerToggle actionBarDrawerToggle;
public NavigationView navigationView;
AlertDialog.Builder reset_alert;
LayoutInflater inflater;
FragmentManager fragmentManager;
FragmentTransaction fragmentTransaction;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    //xml map to java
    //btnLogout = findViewById(R.id.btnLogout);
    verifyMsg = findViewById(R.id.verifyEmailMsg);
    verifyEmailBtn = findViewById(R.id.btnVerifyEmail);
    fauth = FirebaseAuth.getInstance();

    reset_alert = new AlertDialog.Builder(this);
    inflater =this.getLayoutInflater();

    //new stuff
    androidx.appcompat.widget.Toolbar toolbar = findViewById(R.id.toolbar2);
    setSupportActionBar(toolbar);

    drawerLayout = findViewById(R.id.drawer);
    navigationView = findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);

    actionBarDrawerToggle = new
            ActionBarDrawerToggle(this, drawerLayout,
            toolbar, R.string.nav_open, R.string.nav_close);

    drawerLayout.addDrawerListener(actionBarDrawerToggle);

    actionBarDrawerToggle.setDrawerIndicatorEnabled(true);
    actionBarDrawerToggle.syncState();

    //fragment manager - creates instance of a fragment
    //load default fragment
    fragmentManager = getSupportFragmentManager();
    fragmentTransaction = fragmentManager.beginTransaction();
    fragmentTransaction.add(R.id.container_fragment,new MainFragment());
    fragmentTransaction.commit();


    //if the user email is not verified still show verify msg
    if(!fauth.getCurrentUser().isEmailVerified()){
        verifyEmailBtn.setVisibility(View.VISIBLE);
        verifyMsg.setVisibility(View.VISIBLE);
    }
    //on click listener for verify email button
    verifyEmailBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //send verification email
            fauth.getCurrentUser().sendEmailVerification()
                    .addOnSuccessListener(new OnSuccessListener<Void>() {
                @Override
                public void onSuccess(Void aVoid) {
                    Toast.makeText(MainActivity.this,"Verification Sent",Toast.LENGTH_SHORT).show();
                    verifyEmailBtn.setVisibility(View.GONE);
                    verifyMsg.setVisibility(View.GONE);
                }
            });
        }
    });

}
//able to select the items in nav drawer
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
    //auto close drawer
    drawerLayout.closeDrawer(GravityCompat.START);
    //Fragment fragment;
    int mId = item.getItemId();
    }
    if (mId == R.id.homeItem){
        //load default fragment
        fragmentManager = getSupportFragmentManager();
        fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.replace(R.id.container_fragment,new MainFragment());
        fragmentTransaction.commit();
    }
    if (mId == R.id.profileSettings){
        fragmentManager = getSupportFragmentManager();
        fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.replace(R.id.container_fragment,new ProfileFragment());
        fragmentTransaction.commit();
    }
    if (mId == R.id.logoutItem){

    }


    return true;
}

@Override
public void onBtnSelected() {
    fragmentManager = getSupportFragmentManager();
    fragmentTransaction = fragmentManager.beginTransaction();
    fragmentTransaction.replace(R.id.container_fragment,new ProfileFragment());
    fragmentTransaction.commit();
} }

MainFragment.java

public class MainFragment extends Fragment {
private onFragmentBtnSelected listener;

@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                         @Nullable Bundle savedInstanceState)
{
   View view = inflater.inflate(R.layout.fragment_main,container,false);
   Button clickme = view.findViewById(R.id.clickHF);
   clickme.setOnClickListener(new View.OnClickListener() {
       @Override
       public void onClick(View v) {
           listener.onBtnSelected();
       }
   });
   return view;
}
@Override
public void onAttach(@NonNull Context context){
    super.onAttach(context);
    if(context instanceof onFragmentBtnSelected ){
        listener =(onFragmentBtnSelected) context;
    }
    else {
        throw new ClassCastException(context.toString()   " must implement listiner");
    }
}
public interface onFragmentBtnSelected{
    public void onBtnSelected();
}

}

nav_menu.xml

<?xml version="1.0" encoding="utf-8"?>
<item android:title="General">
    <menu>
        <item
            android:id="@ id/homeItem"
            android:icon="@drawable/ic_baseline_home_24"
            android:title="@string/Home" />

    </menu>
</item>
<item android:title="Account Settings">
    <menu>
        <item
            android:id="@ id/profileSettings"
            android:icon="@drawable/ic_baseline_account_circle_24"
            android:title="Profile" />

    </menu>
</item>
<item android:title="App Features">
    <menu>
        <item
            android:id="@ id/logoutItem"
            android:icon="@drawable/ic_baseline_power_settings_new_24"
            android:title="@string/logout" />
    </menu>
</item></menu>

Any help would be greatly appreatiated , having trouble best utilizing fragments in a navigation drawer

CodePudding user response:

Mainactivity.java:

onNavigationItemSelected method inside this without Alert Dialog

if (mId == R.id.logoutItem){
            FirebaseAuth.getInstance().signOut();
            startActivity(new Intent(getApplicationContext(),LoginActivity.class));
            finish();
 }

with Alert Dialog use

if (mId == R.id.logoutItem){
 MaterialAlertDialogBuilder(this)
                .setTitle("Title")
                .setMessage("Message")
                .setIcon(android.R.drawable.ic_dialog_alert)
                .setPositiveButton("Ok") { _, _ ->
                    FirebaseAuth.getInstance().signOut();
                    startActivity(new 
                    Intent(getApplicationContext(),LoginActivity.class));
                    finish();
                }
                .setNegativeButton("Cancel") { _, _ ->
                    Toast.makeText(this, "clicked Cancel", Toast.LENGTH_LONG).show()
                }
                .show()
 }
  •  Tags:  
  • Related