What is diffrence between back button and setDisplayHomeAsUpEnabled in an activity? - java

I have two activtiy. When a boolean variable in activity 1 is true then the UI in activity 2 should be update (activity 2 is with fragment). When I back to activity 2 with (setDisplayHomeAsUpEnabled) it works correctly but with back button it does not work. What is the difference between this ways and how I can solve this. I try update the activity 2 with this code but it does not work:
#Override
public void onBackPressed() {
super.onBackPressed();
//update();
}

The Home Button is not meant to behave like the Back Button. See this reference. The Home or "Up" Button should take the user up within the view hierarchy (i.e. if you have a number of multiple choice fragments, don't go back through each of them, but back to the activity that started the first fragment)
Each activity should specify what it's parent activity is in order to properly use this functionality. You can do this through the manifest, or by overriding onOptionsItemSelected() as outlined here
In terms of why your activity 2 may be updating when using the "Up" button but not the back button, this could be because both handle the back stack in a different way. Back will take you to the last thing on the stack and resume it, assuming you don't haven't tagged the activity with a launchmode that alters this behavior. Here's more info on the back stack. If you haven't designated your Activity 2 as "singletop" then when you use the "Up" Button, a new instance of that parent activity is created. See here. This may means that the information is updating after using the home button because it's creating a new instance of the activity, while for the back button - you are not creating a new instance but resuming a previous instance... make sure you implement an onResume() function to properly handle this and update the information.

Related

Up Navigation: From Activity to Fragment: Android Studio

The basic navigation of my app is a tab bar within one activity in which each tab is its own fragment. I am trying to get the back button to work to go back to the last tab it was on. I can get the back button to work/appear if the activities are going to the first tab by using this in the java class of the activity:
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
and this in the AndroidManifest.xml:
<activity android:name=".CreateNewPost" android:parentActivityName=".MainActivity"></activity>
This works fine, however when I go to a new activity from a button within the other tabs, if I use this same method it goes to tab1. How do I tell it to go to a specific tab or the last active fragment?
Any suggestions would help!
When you launch a new activity the old one either paused or stopped , as in either OnPause() or OnStop() method has been called. Then when you navigate back to a previous activity it is either started (OnStart()) or resuemd (OnResume()). And sometime the activity is destroyed and created again when navigating back to it using OnDestroy() and OnCreate() respectively.
The most guaranteed way that I can think of is to store the state of the first activity somewhere persistently and when the user navigates back to it check what has been stored and show that fragment.
You can use SharedPreferences to store this kind of data, see the google developer documentation on that here. Or onSaveInstanceState(Bundle savedInstanceState) check out this SO question on saving activity state. Although from the answers it is clear that onSaveInstanceState should not work in your specific case, but you should look at it any way because it is useful in other cases like changing screen orientation for example.

how to make the appliction exit when pressing back button in the main activity?

In my application when i click the back button it passes through all the activities that i open them previously , i used the public void onBackPressed() method to make the back button back to the activity that i want as follow
public void onBackPressed()
{
startActivity(new Intent("com.MyDiet.Main"));
Tracker.this.finish();
}
is that true and safe way to code the back button ? how i can prevent the application from passing through all the previous opened activities when the back button is pressed ? and how i can make the application exit when i click the back button in the main activity?
In your application, and in ALL android applications, unless it's critical not to pass through unneeded steps (such as login if you're already logged in), it's VERY important not to override Android standard behaviour. Users normally complain about Android apps not having a common behaviour or style guideline.
Anyway, yeah, you can just override onBackPressed on all your activities and do whatever you want. But just don't.
This approach isn't good, because you're polluting the activity stack of your application
Example:
current stack: MainAct -> Act2 -> Act3 (we're in activity 3)
With your code above, when you press back, the stack now looks as follows:
MainAct -> Act2 -> MainAct
Because you ended Act3 and launched a NEW main activity, which may be not what you wanted.
To achieve what you want (Get back to main when the current activity is over) you need to work on the intermediate activities: In the example above, when from Act2 you call startActivity("Act3"), you should call "this.finish()". Therefore you don't have to override "onBackPressed()" of activity 3: simply the default value will terminate Act3 and the next activity in the stack will be MainAct
MainAct -> A2 (A2 launches A3 and then calls this.finish())
MainAct -> A3 (user now press back)
MainAct (the mainactivity is now on top)
To summarize, you don't have to override onBackPressed, you just have to correctly manage the lifecycle of the activity between the main one and the current one.
Generally speaking it's not recommended to make things work like user doesn't expect and that is considered as very bad practice. That's why it is not good to start activity from overriden onBackPressed().
When user press back by default activity will finish and one from back stack will be displayed. You as developer will (by writing code) decide which one is that. You can do it this way but later (or for somebody else) it will be a bit messy and difficult to find this unusual place for code which is starting other activity.
So..It would be useful to read about activity lifecycle and back stack to get impression how it works and understand terminology better.
If you want one of your activity not to stay on back stack you can add in manifest file file android:noHistory="true" for that activity.
Same thing you can achieve from code by adding appropriate flag to intent when you start activity: Intent.FLAG_ACTIVITY_NO_HISTORY
When user "go away" from ActivityOne (started using intent or defined in manifest like described), to new ActivityTwo and then press back, it will not go to ActivityOne because it will not be on back stack. Using this you can precisely control navigation through your activities.
More flags are available for use, but I guess this is what you wanted to achieve.
Hope you will find my answer useful. Cheers..
You can use a lot of tricks to exit your complet application for my part i use this start a intent and then from the androidmanifest i choose the category to home and than close the current activity such would be your mainactivity !
public void onBackPressed() {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
}

Pop Activity From Stack onResume

When my program starts, it runs a mainActivity, which right away launches and loads data into another Activity. I do this because the data needs only be loaded once, in mainActivity, then sent along to the other activities!
So! With that being said, my problem is probably forseeable! When the user clicks back enough, he will get to this initial activity, and sit there... ungracefully, instead of going back to Android's main menu.
What I want to do is add something to the onResume() method of the mainActivity, so that when it is re-entered I "activate" the back button from within the code-- (a boolean flag makes sure I'm not doing this incorrectly, thus I know it was on a back click). So isn't this just popping the current Activity from the Activity Stack?
how do I pop an activity from the activity stack!
Thanks!
Instead of using the "noHistory" attribute,you can also call finish() as you launch your next activity.. It will not re-appear when you then hit the "back" button.This will close the first activity.. removing it from the stack..
Use no history option so that this activity never gets onto the backstack.
android:noHistory=["true" | "false"]

Is it possible to force Activities to get re-drawn when the back key is used?

I understand the concept of the back-stack, so I'm pretty sure this isn't possible but thought I'd ask anyway.
If it isn't, then what is the approach to simulate this behavior? For instance, I have an Activity "A1" that starts another Activity "A2". "A2" alters the content that "A1" shows. When the back button is pressed, the old "A1" is displayed with the old content. Whenever "A1" is called again then the new "A1" will show the new content.
How do developers get around this issue?
When a user press the back-button the A1 activity comes back to the foreground. This will not trigger the onCreate() so you can't use that but if you look at the Activity Lifecycle the onResume() method will be called.
So if you move the displaying of the content in activity A1 from the onCreate() to the onResume() method it should work fine in both situations, when the activity is started and when you return to the activity using the back-button.
Check the Activity Lifecycle. When an activity is made visible it will go through onStart and then onResume when it gains focus. You can load new content at one of these points instead of in onCreate if you would like to update whenever the user navigates there.

Navigate to previous Activity

I have two screens, in second screen i have one back button that shows the first screen(using intent). if i click that back button from second screen i navigated to first screen no probs in that.. now i want to navigate back to second screen automatically without clicking any button. Please help me how can i do this. Thanks for ur valuable time .
I would give a try to a ViewFlipper activity, with two screens. This, of course, if you can encapsulate your actions into one activity (which i'm sure is manageable with AsyncTasks / Threads, Services and Handlers).
This way you can use gestures, (soft/hard)buttons, dropdowns, -whatever-, to navigate between your screens.
You can automatically go back to a previous activity on the Activity stack by calling the finish() method.
If you want to do this without any user interaction, use a Handler that automatically calls finish() on your activity after a predefined timeout (see this article for more information on Handlers).
try with Thread.sleep([ms]) and then call finish or call intent to the first
The one solution is, when you press BACK button from second screen instead of call finish(); you should start first activity again, so the activity stack will be
FIRST
SECOND
FIRST
so after the delay of two second your activity will finish and eventually will come back to second screen, and state will be maintained also.

Categories

Resources