Question

so I am new to android development and I am stuck with small problem. I got this code: `

Button button2=(Button)findViewById(R.id.button2);
    button2.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        startActivity(new Intent(Menu.this, pistols.class));
        finish();
    }

});`

That part is working fine, but when I start next Activity, and I want to return to previous activity using hardware device button(back button) it closes application instead of returing me to previous activity. What should I do?

Was it helpful?

Solution 2

This one helps

Button button2=(Button)findViewById(R.id.button2);
button2.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
    // TODO Auto-generated method stub
    startActivity(new Intent(Menu.this, pistols.class));

}});

another way around. you can override onBackPressed. start the first activity from there.

@Override
public void onBackPressed() {
    super.onBackPressed();
// call the first activity here
    this.finish();
}

OTHER TIPS

Remove finish(). It should fix it, because you call `finish() it kills the activity and removes it from the back stack thus you can't return to it by pressing the back button.

Button button2=(Button)findViewById(R.id.button2);
    button2.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        startActivity(new Intent(Menu.this, pistols.class));

    }

});`

Remove finish

please search or do RnD about the activityforresult

in your code startactivity(...) will start the new activity and the very next line i.e finish() will finishes the current activity. so you cannot return to previous activity after you have pressed back button.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top