In the navigation drawer I have a logout item and when I click on it I call a logout method but it's not executing any of the code inside this method.
This is the logout method, the first system.out.println does appear in the console but the one inside the onClick doesn't
public void logout() {
System.out.println("inside logout method");
logoutBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
System.out.println("inside logout onclick");
Call<Void> call = apiInterface.LogoutUser();
call.enqueue(new Callback<Void>() {
@Override
public void onResponse(Call<Void> call, Response<Void> response) {
if (!response.isSuccessful()) {
FancyToast.makeText(MainActivity.this,
"Ha sucedido un error, intente de nuevo.",
FancyToast.LENGTH_SHORT, FancyToast.CONFUSING,
R.drawable.error_outline, false).show();
return;
}
SharedPreferencesHelper.removeUser(MainActivity.this);
Intent i = new Intent(MainActivity.this, LoginActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(i);
}
@Override
public void onFailure(Call<Void> call, Throwable t) {
FancyToast.makeText(MainActivity.this,
"Ha sucedido un error, intente de nuevo.",
FancyToast.LENGTH_SHORT, FancyToast.CONFUSING,
R.drawable.error_outline, false).show();
return;
}
});
}
});
This is where I'm calling it, I do get the Toast message when I click on it
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.nav_calendar:
getSupportFragmentManager().beginTransaction()
.replace(R.id.fragment_container, new CalendarFragment()).commit();
break;
case R.id.nav_survey:
getSupportFragmentManager().beginTransaction()
.replace(R.id.fragment_container, new SurveyFragment()).commit();
break;
case R.id.nav_forum:
getSupportFragmentManager().beginTransaction()
.replace(R.id.fragment_container, new ForumFragment()).commit();
break;
case R.id.nav_logout:
logout();
FancyToast.makeText(MainActivity.this,
"item clicked.",
FancyToast.LENGTH_SHORT, FancyToast.CONFUSING,
R.drawable.error_outline, false).show();
break;
}
drawer.closeDrawer(GravityCompat.START);
return true;
}
What am I doing wrong?
logout()method is doing, basically, is setting theOnClickListeneronlogoutBtn. You would then need to clicklogoutBtnfor theonClick()method to run. It's not really clear what setup you're trying to effect, there. Perhaps you want all of that network code directly insidelogout(), and then to calllogout()fromlogoutBtn'sonClick(), too? Do you mean to have both aButtonand a menu item to logout with?