-1

I have two activities, How is it possible to go back to a previous activity.

What code do I need to go back to previous activity

ADM
  • 20,406
  • 11
  • 52
  • 83
iam_aliyas
  • 11
  • 5

4 Answers4

2

Assuming you started the new activity with

startActivity(new Intent(this, SecondActivity.class));

puts the SecondActivity in front and the FirstActivity in the backstack. To go back to the FirstActivity, put this in your second activity.

finish();
THGRoy
  • 43
  • 11
1

If you start the activity with result like below :

From 1st Activity :

startActivityForResult(new Intent(this, SecondActivity.class),requestCode);

You can finish the activity with required intents :

From 2nd Activity :

// Optional if you want to pass values from second activity to first
Intent data = new Intent();
data.putExtra("key","any_value");
setResult(RESULT_OK,data);

// Just finish
finish();

Refer the below link for more information like onActivityResult callback and more https://developer.android.com/training/basics/intents/result

Googlian
  • 6,077
  • 3
  • 38
  • 44
0

1st Method

If you are using Intent then make sure you don't call finish(); method after using the following code,

Intent intent = new Intent(MainActivity.this, SecondActivity.class);
startActivity(intent);

By this code, the Back Button you created will do its work and go to previous Activity.

And also don't override the onBackPressed() method in Activity.

2nd Method

There is another way that you can achieve this by setting Home Button to go to specific Activity, For that, you have to create Back Button in Action Bar in onCreate() method.

getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);

And in the AndroidManifest.xml file, you have to add the following,

    <activity
        android:name="com.example.yourapplication.SecondActivity"
        android:label="@string/title_second_activity"
        android:parentActivityName="com.example.yourapplication.MainActivity" >
        <!-- Parent activity meta-data to support 4.0 and lower -->
        <meta-data
            android:name="android.support.PARENT_ACTIVITY"
            android:value="com.example.yourapplication.MainActivity" />
    </activity>
Hasitha Jayawardana
  • 2,326
  • 4
  • 18
  • 36
0

using intent

  intent = new Intent(this, SecondActivity.class);
            startActivity(intent);

Or you can use onBackPressed() if the activity added to backstack

onBackPressed();
YQadoome
  • 178
  • 14