Vishal
Vishal

Reputation: 49

How to go previous Activity by using back button

I have created two activity i.e Activity A & Activity B ,if i clicked Next Button i.e in Activity A going to Activity B properly But when i click on back button i want to go from Activity B to Activity A and page swipe from left side to right side and on click next page swipe right to left,

here is my code

public void onBackPressed() {
    Intent intent = new Intent(ActivityB.this, Activity.class);
    startActivity(intent);
  finish(); 

Upvotes: 1

Views: 4758

Answers (6)

Rupali Corporation
Rupali Corporation

Reputation: 1

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

Upvotes: 0

Chirag Savsani
Chirag Savsani

Reputation: 6142

Just Remove finish() from Activity.

Because when you go to second activity and finish first activity, there is no any activity and stack.

So If you click back button from second activity, application will be finish if there is no Activity in stack.

You should use this Approach.

Ex.

In Activity.java

Intent first = new Intent(Activity.this,ActivityB.class);
startAcivity(first);
// Don't use finish() here.

In ActivityB.Java

Just click on built in back button.

or If you want to use your own back button.

Use finish(); in button click event.

Upvotes: 1

IntelliJ Amiya
IntelliJ Amiya

Reputation: 75788

You can use only onBackPressed();

   public void onBackPressed() {

        super.onBackPressed();
    }

Android Overriding onBackPressed()

How to go previous Activity by using back button

Upvotes: 1

MurugananthamS
MurugananthamS

Reputation: 2405

 public void onBackPressed() {
    // TODO Auto-generated method stub
        finish();
            super.onBackPressed();
}

Upvotes: 0

Rachita Nanda
Rachita Nanda

Reputation: 4659

Just use finish() no need for intent as A is already in stack and when you finish B, A will come to surface

 public void onBackPressed() {

        finish(); 

     }

Read this to learn more about android activity stack.

Upvotes: 0

bhanu.cs
bhanu.cs

Reputation: 1365

No need to put an intent and start a new activity that would take you to previous activity.

Just call 'finish()'

It would go back to previous activity as Android activities are stored in the activity stack

If you have other activities that are present in between the activites say if android stack is filled with Activity A>Activity C>Activity B,If you want to go to Activity A on finish of Activityy B then you have to set an intent flag like FLAG_ACTIVITY_REORDER_TO_FRONT or FLAG_ACTIVITY_PREVIOUS_IS_TOP

Upvotes: 0

Related Questions