android - onBackPressed() not working for me

I would suggest you to use ActionBar as suggested by WarrenFaith in the comments below. Pls check the link below for more information

http://developer.android.com/design/patterns/navigation.html

Here's a tutorial for the same

http://www.vogella.com/articles/AndroidActionBar/article.html

You can use this. However this also seems to be a bad design. You can check the comments below to know why

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK) {
        onBackPressed();
    }
    return super.onKeyDown(keyCode, event);
}

public void onBackPressed() {
    Intent myIntent = new Intent(MyActivity.this, MainActivity.class);

    myIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    startActivity(myIntent);
    finish();
    return;
}

Onn back button pressed inn your current activity when you back press you clear the activity stack and naviagate to MainActivity.

Also i would suggest no to display a alert dialog on back button press. Its a bad design. You can search on SO. i read the same and was answered by commonsware


@Override
public void onBackPressed() {
    super.onBackPressed();
    int count = getSupportFragmentManager().getBackStackEntryCount();
    Log.e("count", "is getBackStackEntryCount -> " + count);
    for (int i = 0; i < count; ++i) {
        getSupportFragmentManager().popBackStackImmediate();
        Log.e("getBackStack", "IS REMOVED " + i);
    }
    // toolbar.setTitle("Dashboard");
}

Tags:

Android