How avoid returning to login layout pressing the back button/key?

SoldierCorp picture SoldierCorp · Apr 20, 2012 · Viewed 11.6k times · Source

I want create an app for my institute.

The problem is: my application will have two layouts (login and dashboard).

Students can correctly fill out the login form, enter the dashboard, press buttons, and fill other fields. But if the user then presses the back button, it should not return to the login screen, but remain in the dashboard, or failing that, exit the application.

Then if a student reopens the application and it's already logged, he should be automatically redirected to the dashboard, and not the login screen, unless the user press the logout button on the dashboard, then redirect him back to the login screen.

How could you do that?

Edit: I implemented 2 intents and 2 activities, and new questions arose me is that when I press the home button and from the taskmanager I open the app, open in the activity that was left, but if the open from the icon to open the app again from the first activity, as do to open in the last one was left?

Answer

Enrique Marcos picture Enrique Marcos · Apr 20, 2012

I've implemented something similiar using SharedPreferences. I did this:

LoginActivity

SharedPreferences settings;
public void onCreate(Bundle b) {
    super.onCreate(b);
    settings = getSharedPreferences("mySharedPref", 0);
    if (settings.getBoolean("connected", false)) {
        /* The user has already login, so start the dashboard */
        startActivity(new Intent(getApplicationContext(), DashBoardActivity.class));
    }
    /* Put here the login UI */
 }
 ...
 public void doLogin() {
    /* ... check credentials and another stuff ... */
    SharedPreferences.Editor editor = settings.edit();
    editor.putBoolean("connected", true);
    editor.commit();
 }

In your DashBoardActivity override the onBackPressed method. This will take you from DashBoardActivity to your home screen.

@Override
public void onBackPressed() {
    Intent intent = new Intent(Intent.ACTION_MAIN);
    intent.addCategory(Intent.CATEGORY_HOME);
    startActivity(intent);
}  

Hope it helps.