Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

onkeyDown / onBackPressed are not working with intent?

This is a simple operation and seems to be working until I've changed my minSdk = 8 to 9 , and targetSdk remains 21 in my manifest. Problem is that i have an activity A , and i am going to activity B when a button is pressed in activity A . Now on activity B whenever someone press back button i want to clear the activity stack and transfer my activity B to activity C . but instead it finish activity B and go to Activity A , so far i have tried onKeyDown , onBackPressed , nothing seems to work , kindly help.

Activity A (in onClick method):

Intent in = new Intent(A.this,
                            B.class);
in.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
                            | Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(in);

[UPDATED]Activity B :

@Override
public void onBackPressed() {
    Intent in = new Intent(this, C.class);
    Bundle bundle = new Bundle();
    bundle.putSerializable("Scores", score);

    in.putExtras(bundle);

    startActivity(in);
}

Activity C:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.C);
    ScoreSaver scores = (ScoreSaver) getIntent().getExtras().getSerializable("Scores");
}

2 Answers

Add android:noHistory="true" to both Activity A and B in your manifest file. This way these activities won't be in your back stack. In Activity B you have to override the behavior of onBackPressed(). It has to look like this:

@Override
public void onBackPressed() {
    Intent intent = new Intent(this, ActivityC.class);
    startActivity(intent);
}

If you leave super.onBackPressed() in your method, the default behavior will happen, i.e. Activity B will be closed and you jump back to Activity A.

like image 78
Chris Fox Avatar answered Dec 16 '25 22:12

Chris Fox


Issue was with Serializable object which was using storing context which will be null in next activity , which causes exception , that crashes my activity. so i removed it everything works fine. Thanks @Chris Fox


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!