what is happening here is that, on once pressing the back button activity reloads again and again pressing back button it exits the app. I want it to be on one time i.e on first time
I have tried so many ways like experimenting with onBackPressed method, but none of it worked. I want to fix that, when user presses the back button he should be exited from the app. Same is happening in other activity also, in which I have a login page, in which once user comes to login page, if he wishes to exit the app and presses the back button, then in my case login page is again reloaded and then after pressing back button again it exits the app.
Below is the code.
public class MainActivity extends AppCompatActivity {
CardView attendance, time_table, directory, daily_work, notices, transport,remarks,calendar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SharedPreferences preferences = getSharedPreferences("user_login",MODE_PRIVATE);
boolean isLogin = preferences.getBoolean("isLogin", false);
if(isLogin)
{
init();
methodListener();
}
else {
Intent intent = new Intent(this, Login.class);
startActivity(intent);
finish();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main_menu, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.logout) {
SharedPreferences preferences = getSharedPreferences("user_login", MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.clear();
editor.commit();
Intent intent = new Intent(this,Login.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivity(intent);
finish();
}
return super.onOptionsItemSelected(item);
}
}
Please suggest some ways to fix it.
use onBackPressed() like below
@Override
public void onBackPressed() {
AlertDialog.Builder builder1 = new AlertDialog.Builder(HomeActivity.this);
builder1.setTitle("Close...?");
builder1.setMessage("Do you want to exit?");
builder1.setCancelable(true);
builder1.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
@Override
public void onClick(DialogInterface dialog, int id) {
// Home.this.finish();
finishAffinity();
}
});
builder1.setNegativeButton("No", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert11 = builder1.create();
alert11.show();
}