user3231871
user3231871

Reputation: 191

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?

Upvotes: 0

Views: 995

Answers (5)

Krish4906
Krish4906

Reputation: 157

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.

Upvotes: 0

user2323471
user2323471

Reputation: 85

please search or do RnD about the activityforresult

Upvotes: 0

ASP
ASP

Reputation: 1974

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

Upvotes: 0

Aashir
Aashir

Reputation: 2621

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.

Upvotes: 3

Digvesh Patel
Digvesh Patel

Reputation: 6533

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

Upvotes: 0

Related Questions