I want to do something simple on android app.
How is it possible to go back to a previous activity.
What code do I need to go back to previous activity
Android activities are stored in the activity stack. Going back to a previous activity could mean two things.
You opened the new activity from another activity with startActivityForResult. In that case you can just call the finishActivity() function from your code and it'll take you back to the previous activity.
Keep track of the activity stack. Whenever you start a new activity with an intent you can specify an intent flag like FLAG_ACTIVITY_REORDER_TO_FRONT or FLAG_ACTIVITY_PREVIOUS_IS_TOP. You can use this to shuffle between the activities in your application. Haven't used them much though. Have a look at the flags here: http://developer.android.com/reference/android/content/Intent.html
As mentioned in the comments, if the activity is opened with startActivity() then one can close it with finish().
If you wish to use the Up button you can catch that in onOptionsSelected(MenuItem item) method with checking the item ID against android.R.id.home unlike R.id.home as mentioned in the comments.
Try Activity#finish(). This is more or less what the back button does by default.
Just write on click finish(). It will take you to the previous Activity.
Just this
super.onBackPressed();
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
This will get you to a previous activity keeping its stack and clearing all activities after it from the stack.
For example, if stack was A->B->C->D and you start B with this flag, stack will be A->B
Just call these method to finish current activity or to go back by onBackPressed
finish();
OR
onBackPressed();
Are you wanting to take control of the back button behavior? You can override the back button (to go to a specific activity) via one of two methods.
For Android 1.6 and below:
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
// do something on back.
return true;
}
return super.onKeyDown(keyCode, event);
}
Or if you are only supporting Android 2.0 or greater:
#Override
public void onBackPressed() {
// do something on back.
return;
}
For more details: http://android-developers.blogspot.com/2009/12/back-and-other-hard-keys-three-stories.html
Try this is act as you have to press the back button
finish();
super.onBackPressed();
Add this in your onCLick() method, it will go back to your previous activity
finish();
or You can use this. It worked perfectly for me
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if ( id == android.R.id.home ) {
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
if you want to go to just want to go to previous activity use
finish();
OR
onBackPressed();
if you want to go to second activity or below that use following:
intent = new Intent(MyFourthActivity.this , MySecondActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//Bundle is optional
Bundle bundle = new Bundle();
bundle.putString("MyValue1", val1);
intent.putExtras(bundle);
//end Bundle
startActivity(intent);
If you have setup correctly the AndroidManifest.xml file with activity parent, you can use :
NavUtils.navigateUpFromSameTask(this);
Where this is your child activity.
Got the same problem and
finish(); OR super.onBackPressed();
worked fine for me, both worked same, but no luck with return
You can explicitly call onBackPressed is the easiest way
Refer Go back to previous activity for details
Start the second activity using intent (either use startActivity or startActivityForResult according to your requirements). Now when user press back button, the current activity on top will be closed and the previous will be shown.
Now Lets say you have two activities, one for selecting some settings for the user, like language, country etc, and after selecting it, the user clicks on Next button to go to the login form (for example) . Now if the login is unsuccessful, then the user will be on the login activity, what if login is successful ?
If login is successful, then you have to start another activity. It means a third activity will be started, and still there are two activities running. In this case, it will be good to use startActivityForResult. When login is successful, send OK data back to first activity and close login activity. Now when the data is received, then start the third activity and close the first activity by using finish.
You can try this:
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
finish();
return true;
}
return super.onKeyDown(keyCode, event);
}
All new activities/intents by default have back/previous behavior, unless you have coded a finish() on the calling activity.
#Override
public void onBackPressed() {
super.onBackPressed();
}
and if you want on button click go back then simply put
bbsubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
I suggest the NavUtils.navigateUpFromSameTask(), it's easy and very simple, you can learn it from the google developer.Wish I could help you!
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if ( id == android.R.id.home ) {
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
Try this it works both on toolbar back button as hardware back button.
There are few cases to go back to your previous activity:
Case 1: if you want take result back to your previous activity then
ActivityA.java
Intent intent = new Intent(ActivityA.this, FBHelperActivity.class);
startActivityForResult(intent,2);
FBHelperActivity.java
Intent returnIntent = new Intent();
setResult(RESULT_OK, returnIntent);
finish();
Case 2: ActivityA --> FBHelperActivity---->ActivityA
ActivityA.java
Intent intent = new Intent(ActivityA.this, FBHelperActivity.class);
startActivity(intent);
FBHelperActivity.java
after getting of result call finish();
By this way your second activity will finish and because
you did not call finish() in your first activity then
automatic first activity is in back ground, will visible.
Besides all the mentioned answers, their is still an alternative way of doing this, lets say you have two classes , class A and class B.
Class A you have made some activities like checkbox select, printed out some data and intent to class B.
Class B, you would like to pass multiple values to class A and maintain the previous state of class A, you can use, try this alternative method or download source code to demonstrate this
http://whats-online.info/science-and-tutorials/125/Android-maintain-the-previous-state-of-activity-on-intent/
or
http://developer.android.com/reference/android/content/Intent.html
Just try this in,
first activity
Intent mainIntent = new Intent(Activity1.this, Activity2.class);
this.startActivity(mainIntent);
In your second activity
#Override
public void onBackPressed() {
this.finish();
}
First, thing you need to keep in mind that, if you want to go back to a previous activity. Then don't call finish() method when goes to another activity using Intent.
After that you have two way to back from current activity to previous activity:
Simply call:
finish()
OR
super.onBackPressed();
To go back from one activity to another by clicking back button use the code given below use current activity name and then the target activity.
#Override
public void onBackPressed() {
// do something on back.
startActivity(new Intent(secondActivity.this, MainActivity.class));
return;
}
I have three activities: First, Second and Third. I used this method in Second activity:
public void onBackPressed() {
super.onBackPressed();
finish();
}
and this on Third activity:
public void onBackPressed() {
super.onBackPressed();
Intent i = new Intent(Third.this, Second.class);
startActivity(i);
finish();
}
The problem is when I press back button after coming from the Third activity, I am going into First activity instead of finish(). I am successfully exiting the application when I click back button right after coming from first activity but not after coming from Third activity.
How to solve this problem?
EDIT: Thanks for the answers guys,the answer of "Ved Prakash" solved the problem for me.But i have a weird problem now.When i press back button the app is successfully exiting but the app which i minimized to Recent Apps button is coming on to the screen and exiting.For example,if i have opened Setting app before opening my app,when i press back button,my app is exiting and immediately Settings app is also opening and exiting itself.What might be the problem?
Your problem is that you don't seem to understand how Activities work. The finish() function ends the current Activity, and then you receive the previous Activity from the backstack.
My recommendation is that you should use a single Activity, and hold Fragments inside it. If you want it so that pressing the Back button ends the application at any screen that is displayed, you could do the following:
Activity XML:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/initial_container"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
Activity that holds the Fragments:
public class InitialActivity extends FragmentActivity implements ReplaceWith
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_initial);
getSupportFragmentManager().addOnBackStackChangedListener(new OnBackStackChangedListener()
{
public void onBackStackChanged()
{
int backCount = getSupportFragmentManager().getBackStackEntryCount();
if (backCount == 0)
{
finish();
}
}
});
if (savedInstanceState == null)
{
getSupportFragmentManager().beginTransaction().add(R.id.initial_container, new FirstFragment()).commit();
}
}
#Override
public void replaceWith(Fragment fragment)
{
getSupportFragmentManager().beginTransaction().replace(R.id.initial_container, fragment).commit();
}
}
Example for a Fragment:
public class FirstFragment extends Fragment implements View.OnClickListener
{
private ReplaceWith activity_replaceWith;
private ImageView exampleImage;
public FirstFragment()
{
super();
}
#Override
public void onAttach(Activity activity)
{
super.onAttach(activity);
try
{
activity_replaceWith = (ReplaceWith) activity;
}
catch (ClassCastException e)
{
Log.e(getClass().getSimpleName(), "Activity of " + getClass().getSimpleName() + "must implement ReplaceWith interface!", e);
throw e;
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View rootView = inflater.inflate(R.layout.fragment_first, container, false);
exampleImage = (ImageView) rootView.findViewById(R.id.fragment_first_example_image);
exampleImage.setOnClickListener(this);
return rootView;
}
#Override
public void onClick(View v)
{
if(v == exampleImage)
{
activity_replaceWith.replaceWith(new SecondFragment());
//please note that this should be done only if you are planning
//only on single-screen applications
//with no other layouts based on orientation or size
//otherwise, the Activity needs to be responsible for this, not the Fragment
}
}
}
This way, when you press the Back button, your application would end from any displayed screen.
Ok your code is wrong.
If you will look at activity source, you see that activity.onBackPressed() is calling finish(). So if call super.onBackPressed() you don't need to call finish.
Finish() is not stopping your application, it's stopping current activity.
Your code on third activity very strange. You are trying to stop activity and start another same activity.
What exactly you want to achieve?
If you want to exit application from your third activity, you need to clear your backstack. But I think you have problem with structure of your app.
Ok. then you should finish your first activity when you go to second activity like this(If you are using intent for that):
Intent it=new Intent(FirstActivity.this,SecondActivity.class);
finish();
startactivity(it);
and same for Second Activity:
Intent it=new Intent(SecondActivity.this,ThirdActivity.class);
finish();
startactivity(it);
this done your work...when you are in third activity the above activities are finished..
and when you press backButton you will be exit from application..
Good luck.
You can use -
public static final int FLAG_ACTIVITY_CLEAR_TOP
If set, and the activity being launched is already running in the
current task, then instead of launching a new instance of that
activity, all of the other activities on top of it will be closed and
this Intent will be delivered to the (now on top) old activity as a
new Intent.
And here is how -
When the user wishes to exit all open activities, they should press a button which loads the first Activity that runs when your app starts, in my case "MainActivity".
Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("EXIT", true);
startActivity(intent);
The above code clears all the activities except for LoginActivity. LoginActivity is the first activity that is brought up when the user runs the program. Then put this code inside the LoginActivity's onCreate, to signal when it should self destruct when the 'Exit' message is passed.
if (getIntent().getBooleanExtra("EXIT", false)) {
finish();
}
This explanation part is also introduced at exit-an-android-app.
Please help me.
I use onOptionsItemSelected to get to settings layout. There I activate setDisplayHomeAsUpEnabled
public boolean onOptionsItemSelected(MenuItem settings){
setContentView(R.layout.settings);
getActionBar().setDisplayHomeAsUpEnabled(true);
return super.onOptionsItemSelected(settings);
}
How can I get back to main layout from settings layout?
In onOptionsItemSelected you need to find out whether the MenuItem that is clicked is your Home item.
I would use a switch like:
switch (settings.getItemId()) {
// If home icon is clicked return to main Activity
case android.R.id.home:
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
break;
}
Then I would either start the MainActivity again or just call finish() to end the current one. There is a very nice article with loads of samples which you might find useful here: http://www.vogella.com/articles/AndroidActionBar/article.html
So, I have a menu activity and there a user can choose a game to play. When he does that, in game he has an option to go back to menu (either on backPress or on my Exit button in game). I need, when that happens, to disable that game button, so the user cannot play it again. How can I do that?
I tried to make an object from Menu class and then disable the button but get error. Also tried:
public void disableButton(){
button.setEnabled(false);
}
and then calling it:
obj.disableButton
But I get stactOverflow errors on line where I created my obj as soon my menu activity starts. How to do this?
EDIT:
In Menu class:
public void disableButton(){
button.setEnabled(false);
}
In Game class:
Menu objMenu = new Menu();
And then in exit onClickListener:
objMenu.disableButton();
EDIT2:
Here's how I call my game activity:
Intent i = new Intent(this, Game.class);
startActivityForResult(i, GAME);
Then in game activity:
Intent resp = new Intent();
resp.putExtra("score", numberOfPoints);
setResult(1, resp);
finish();
And again in Menu class:
final private static int AS = 1;
#Override
protected void onActivityResult(int reqCode, int respCode, Intent i) {
if(respCode == 1) {
switch(reqCode) {
case AS: receivedA = i.getIntExtra("score", receivedA);
button.setEnabled(false);
break;
}
So, this is what I do when game ends, and I disable that button succesfully.
I think the issues is not only in button.setEnabled(false);. As it is hard to say what is the problem without seeing code's details, I am suggesting another solution
start the game activity from menu activity using startActivityForResult
when the game is finished ,in the return intent put a specific data
In Menu activity, in onActivityResult check if the result intent has that specific data
basing on step 3 you can enable or disable the button
I started programming for android with eclipse a few days ago
However, I am stuck now.
I would like to add a new activity, so that i can add a new screen with new layout (an info screen about the app)
It is made so that when you press a specific menu button (help) it launches the help.xml activity and shows a new screen with some new words.
This succeeded one time, but I cant manage to do this another time.
Here is the code to direct to the activity, made from the main.java:
#Override
public boolean onCreateOptionsMenu (Menu menu) {
getMenuInflater().inflate (R.menu.menu, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId())
{
case R.id.help:
Intent intent = new Intent(this, help.class);
startActivity(intent);
case R.id.quit:
System.exit(0);
break;
I dont have code in the help.java, and I have made some buttons in help.xml
The 'quit' button works fine but the help thing doesnt.
I am also very unsure where it links to, as the previous time I had to both make a help.java and a help.xml activity.
I already noted the help activity in the manifest.xml
Help would be appreciated, thanks in advance!
You forgot to write break after starting new Activity. That was the issue.
Replace this code:
case R.id.help:
Intent intent = new Intent(this, help.class);
startActivity(intent);
case R.id.quit:
System.exit(0);
break;
with
case R.id.help:
Intent intent = new Intent(this, help.class);
startActivity(intent);
break;
case R.id.quit:
System.exit(0);
break;
you forgot the break, and then in your help class
public class help extends Activity
{
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.help);
}
}