Navigate up not working - android

I have three activities A->B->C. Sometimes I launch Activity C directly from A. Even then, when the user presses the "up" button, I want to go to activity B. So after a lot of searching, I am doing this:
AndroidManifest.xml
<activity
android:name=".B"
android:parentActivityName=".A"
android:launchMode="singleTop"/>
<activity
android:name=".C"
android:parentActivityName=".B"/>
In Activity C:
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
....
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
Intent upIntent = NavUtils.getParentActivityIntent(this);
upIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
NavUtils.navigateUpTo(this,upIntent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
But when I start activity C from A, the up button just goes back to A, instead of creating a new instance of B.
Even the android docs state:
When you call this method, it finishes the current activity and starts (or resumes) the appropriate parent activity. If the target parent activity is in the task's back stack, it is brought forward.
Am I missing something here?

Related

Android - Navigation Up from Activity to Fragment

I'm developing some application and I have one problem.
I have :
1. Activity A (Navigation Drawer pattern) with ListFragment in FrameLayout:
xml:
<FrameLayout
...>
</FrameLayout>
<LinearLayout
...>
</LinearLayout>
</android.support.v4.widget.DrawerLayout>
Activity B which shows the detail data of ListView in ListFragment.
How can I go back (using Navigation Up Button) from activity B to Activity A with saving UI of the ListFragment (Activity re-creates if I go back using Home Back).
Btw, if I press the back button on my phone, activity does not re-create and returns in previous state.
When you use UP navigation, then the previous activity is recreated. To prevent that from happening while you preserve the UP navigation, you can get the intent of the parent activity, and bring it to front if it exists, otherwise create it if not.
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
Intent parentIntent = NavUtils.getParentActivityIntent(this);
parentIntent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(parentIntent);
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
I also specified launchMode="singleTop" in the Manifest. but I am not sure if that was necessary.
One thing you can do to prevent the first activity to recreate is by just calling finish() on the second activity when that back button is pressed.
Not tested, but I believe the id is android.R.id.home, so all you have to do is override onOptionsItemSelected in the second activity, like this:
/**
* Handles the selection of a MenuItem.
*/
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()){
case android.R.id.home:
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}

Preserve state between activities

I have two different activities, ActA which is my main Activity, and ActB. I get to ActB from ActA through a menu voice. If I press the back button (either software or hardware) in ActB the app come back to ActA preserving my previous state in this activity. If instead I press the up button in the activity bar, the ActA reset its state. How can I prevent this to happen?
Don't know if this could ever help, but this is some code:
Activity A
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
switch (item.getItemId()) {
case R.id.action_save:
startActivity (new Intent (this, Save.class));
return true;
case R.id.action_about:
}
return false;
}
Manifest for Activity B:
<activity
android:name="com.myapplication2.app.Save"
android:label="#string/title_activity_save"
android:parentActivityName="com.myapplication2.app.MainActivity" >
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.myapplication2.app.MainActivity" />
</activity>
Add this switch case:
switch (item.getItemId()) {
case android.R.id.home: finish(); return true;
}
The way it works, Up (android.R.id.home) by default calls your Activity with the same Intent, and depending on how you handled onCreate and onResume it may be the case that you're recreating your views. If you change Up behaviour to match Back the state is preserved.
You won't need android:parentActivityName or meta-data, just add
getActionBar().setDisplayUseLogoEnabled(false);
getActionBar().setDisplayHomeAsUpEnabled(true);
somewhere on your lifecycle code.

Android activity go back to activity that started it instead of parent activity when pressing navigation bar back button

I have the following scenario:
In android manifest I have three activities:
ActivityA
ActivityB - parent of ActivityA
ActivityC
What I want to do is start ActivityA from ActivityC using intent.StartActivity(). The activity is started successfully. Now I want to go back to ActivityC using actionbar's back button (upper left corner), but since ActivityA has ActivityB as parent (as declared in android manifest) the actionbar back button takes me to ActivityB instead of previous ActivityC. If I use the back keyboard button, I get redirected to the ActivityC.
What can I do to get the same result in both "navigate back" cases. The result I'm seeking is to get redirected to the activity that started the ActivityA and not it's parent activity. Is it possible?
You should not define ActivityB as parent for ActivityA in manifest. Instead, handle onOptionsItemSelected in ActivityA like this:
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
}
return super.onOptionsItemSelected(item);
}
When you call startActivity(), do it like that:
Intent intent = new Intent(callingActivity.this, destinationActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
Try the following:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
}
return super.onOptionsItemSelected(item);
}
This will emulate a back button press, which will additionally preserve the state of the Activity you came from (tabs, scroll position).
(Credit goes to #Kise for suggesting this in https://stackoverflow.com/a/31331757/2703209)

Implementing ActionBar Up button

I am implementing the Up button in the ActionBar using this method posted here:
ActionBar Up button and Navigation pattern
It works ok except in one scenario: If Activity A creates Activity B, and then I press Up it will navigate to A no problem.
However, when I get to Activity B, and then I switch to another App, then switch back to my App, and now I press the Up button, it will navigate me to the home screen instead of Activity A.
When I debug I can see that NavUtils.shouldUpRecreateTask(this, upIntent) returns false in both cases, and the upIntent is indeed Activity A for both cases as well. So not sure what the problem is.
#SuppressLint("NewApi")
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int itemId = item.getItemId();
if (itemId == android.R.id.home) {
Intent upIntent = NavUtils.getParentActivityIntent(this);
if (NavUtils.shouldUpRecreateTask(this, upIntent)) {
// This activity is NOT part of this app's task, so create a new task
// when navigating up, with a synthesized back stack.
TaskStackBuilder.create(this)
// Add all of this activity's parents to the back stack
.addNextIntentWithParentStack(upIntent)
// Navigate up to the closest parent
.startActivities();
} else {
// This activity is part of this app's task, so simply
// navigate up to the logical parent activity.
NavUtils.navigateUpTo(this, upIntent);
}
//finish();
return true;
} else if (itemId == R.id.wrap_menu_item) {
wrapText();
invalidateOptionsMenu();
return true;
} else {
return super.onOptionsItemSelected(item);
}
}
Changed Activity A property from
android:launchMode="singleInstance"
to
android:launchMode="singleTask"
resolved the issue. Makes sense because A "singleInstance" activity, permits no other activities to be part of its task. It's the only activity in the task. If it starts another activity, that activity is assigned to a different task. So the only reason Up was working before was because Activity A was "underneath" the previous activity: it gave the illusion it was going back to previous activity.

How can I return to a parent activity correctly?

I have 2 activities (A and B) in my android application and I use an intent to get from activity A to activity B. The use of parent_activity is enabled:
<activity
android:name=".B"
android:label="B" >
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.example.app_name.A" />
</activity>
I also use a theme which provides an UP-button.
So after I called activity B I can use the UP-button to get back to the activity A. The problem is that the application seems to call the onCreate()-function of activity A again and this is not the behaviour I need. I need activity A to look the same way like it looked before I called activity B.
Is there a way to achieve this?
EDIT
I didn't write any code to start activity B from activity A. I think it is auto-generated by Eclipse.
Class B looks like:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_b);
getActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_b, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
You declared activity A with the standard launchMode in the Android manifest. According to the documentation, that means the following:
The system always creates a new instance of the activity in the target
task and routes the intent to it.
Therefore, the system is forced to recreate activity A (i.e. calling onCreate) even if the task stack is handled correctly.
To fix this problem you need to change the manifest, adding the following attribute to the A activity declaration:
android:launchMode="singleTop"
Note: calling finish() (as suggested as solution before) works only when you are completely sure that the activity B instance you are terminating lives on top of an instance of activity A. In more complex workflows (for instance, launching activity B from a notification) this might not be the case and you have to correctly launch activity A from B.
Updated Answer: Up Navigation Design
You have to declare which activity is the appropriate parent for each activity. Doing so allows the system to facilitate navigation patterns such as Up because the system can determine the logical parent activity from the manifest file.
So for that you have to declare your parent Activity in tag Activity with attribute
android:parentActivityName
Like,
<!-- The main/home activity (it has no parent activity) -->
<activity
android:name="com.example.app_name.A" ...>
...
</activity>
<!-- A child of the main activity -->
<activity
android:name=".B"
android:label="B"
android:parentActivityName="com.example.app_name.A" >
<!-- Parent activity meta-data to support 4.0 and lower -->
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.example.app_name.A" />
</activity>
With the parent activity declared this way, you can navigate Up to the appropriate parent like below,
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// Respond to the action bar's Up/Home button
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
So When you call NavUtils.navigateUpFromSameTask(this); this method, it finishes the current activity and starts (or resumes) the appropriate parent activity. If the target parent activity is in the task's back stack, it is brought forward as defined by FLAG_ACTIVITY_CLEAR_TOP.
And to display Up button you have to declare setDisplayHomeAsUpEnabled():
#Override
public void onCreate(Bundle savedInstanceState) {
...
getActionBar().setDisplayHomeAsUpEnabled(true);
}
Old Answer: (Without Up Navigation, default Back Navigation)
It happen only if you are starting Activity A again from Activity B.
Using startActivity().
Instead of this from Activity A start Activity B using startActivityForResult() and override onActivtyResult() in Activity A.
Now in Activity B just call finish() on button Up. So now you directed to Activity A's onActivityResult() without creating of Activity A again..
I had pretty much the same setup leading to the same unwanted behaviour. For me this worked:
adding the following attribute to an activity A in the Manifest.xml of my app:
android:launchMode="singleTask"
See this article for more explanation.
Although an old question, here is another (imho the cleanest and best) solution as all the previous answeres didn't work for me since I deeplinked Activity B from a Widget.
public void navigateUp() {
final Intent upIntent = NavUtils.getParentActivityIntent(this);
if (NavUtils.shouldUpRecreateTask(this, upIntent) || isTaskRoot()) {
Log.v(logTag, "Recreate back stack");
TaskStackBuilder.create(this).addNextIntentWithParentStack(upIntent).startActivities();
} else {
NavUtils.navigateUpTo(this, upIntent);
}
}
[https://stackoverflow.com/a/31350642/570168 ]
But also see: https://speakerdeck.com/jgilfelt/this-way-up-implementing-effective-navigation-on-android
A better way to achieve this is by using two things:
call:
NavUtils.navigateUpFromSameTask(this);
Now, in order for this to work, you need to have your manifest file state that activity A
has a parent activity B. The parent activity doesn't need anything. In version 4 and above you will get a nice back arrow with no additional effort (this can be done on lower versions as well with a little code, I'll put it below)
You can set this data in the manifest->application tab in the GUI (scroll down to the parent activity name, and put it by hand)
Support node:
if you wish to support version below version 4, you need to include metadata as well.
right click on the activity, add->meta data, name =android.support.PARENT_ACTIVITY and value = your.full.activity.name
to get the nice arrow in lower versions as well:
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
please note you will need support library version 7 to get this all working, but it is well worth it!
What worked for me was adding:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onBackPressed() {
finish();
}
to TheRelevantActivity.java and now it is working as expected
and yeah don't forget to add:
getSupportActionbar.setDisplayHomeAsUpEnabled(true); in onCreate() method
I tried android:launchMode="singleTask", but it didn't help.
Worked for me using android:launchMode="singleInstance"
Adding to #LorenCK's answer, change
NavUtils.navigateUpFromSameTask(this);
to the code below if your activity can be initiated from another activity and this can become part of task started by some other app
Intent upIntent = NavUtils.getParentActivityIntent(this);
if (NavUtils.shouldUpRecreateTask(this, upIntent)) {
TaskStackBuilder.create(this)
.addNextIntentWithParentStack(upIntent)
.startActivities();
} else {
NavUtils.navigateUpTo(this, upIntent);
}
This will start a new task and start your Activity's parent Activity which you can define in Manifest like below of Min SDK version <= 15
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.example.app_name.A" />
Or using parentActivityName if its > 15
I had a similar problem using android 5.0 with a bad parent activity name
<activity
android:name=".DisplayMessageActivity"
android:label="#string/title_activity_display_message"
android:parentActivityName=".MainActivity" >
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.example.myfirstapp.MainActivity" />
</activity>
I removed the com.example.myfirstapp from the parent activity name and it worked properly
In Java class :-
toolbar = (Toolbar) findViewById(R.id.apptool_bar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Snapdeal");
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
In Manifest :-
<activity
android:name=".SubActivity"
android:label="#string/title_activity_sub"
android:theme="#style/AppTheme" >
<meta-data android:name="android.support.PARENT_ACTIVITY" android:value=".MainActivity"></meta-data>
</activity>
It will help you
Add to your activity manifest information with attribute
android:launchMode="singleTask"
is working well for me
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// Respond to the action bar's Up/Home button
case android.R.id.home:
finish();
return true;
}
return super.onOptionsItemSelected(item);
like a Back press
try this:
Intent intent;
#Override
public void onCreate(Bundle savedInstanceState) {
intent = getIntent();
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_b);
getActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_b, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
NavUtils.navigateUpTo(this,intent);
return true;
}
return super.onOptionsItemSelected(item);
}
Going into my manifest and adding android:launchMode="singleTop" to the activity did the trick for me.
This specifically solved my issue because I didn't want Android to create a new instance of the previous activity after hitting the Up button in the toolbar - I instead wanted to use the existing instance of the prior activity when I went up the navigation hierarchy.
Reference: android:launchMode
Try this solution use NavUtils.navigateUpFromSameTask(this); in the child activity:
https://stackoverflow.com/a/49980835/7308789
In any context, If you want's to open parent activity on onBackPressed
protected fun navigateToParent() {
NavUtils.getParentActivityIntent(this)?.let { upIntent ->
if (NavUtils.shouldUpRecreateTask(this, upIntent) || isTaskRoot) {
Timber.d("navigateToParent: sourceActivity should recreate")
startActivity(upIntent)
} else {
Timber.d("navigateToParent: sourceActivity in stack, just finish")
}
}
super.onBackPressed()
}
Set android:parentActivityName in manifest
<activity
android:name=".feature.signup.SignUpActivity"
android:parentActivityName=".feature.welcome.WelcomeActivity"
android:windowSoftInputMode="adjustResize" />

Categories

Resources