Search code examples
androidactivity-finishstart-activity

Finishing one activitiy, moving to next activity and then return to previous activity


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?


Solution

  • 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();
    }