Up Navigation: From Activity to Fragment: Android Studio - java

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.

Related

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

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.

Confusion between onPause() onStop() onResume()

I am developing an Android app in which I want to check if the user has minimized the application or just come from another activity.
In detail, if the user have started another app, went to the home screen or locked the screen, I want to show the activity where the user will enter the password to access the app. But where or how to check this exactly?
https://developer.android.com/guide/components/activities/activity-lifecycle.html
I was trying onResume() but according to documentation onResume() can be fired if the user’s navigating to another activity and coming back.
I'm not very clear on what you are trying to achieve.
The life cycle diagram is quite clear if you are wondering which lifecycle method it would hit when something happens.
Basically, it's the same to minimise the app and go to another activity. But if you are referring to coming from another activity in your own app, you can distinguish your own activity by adding extra information to the intent you use.
Basically, it's like this:
Intent intent = new Intent(FirstActivity.this,SecondActivity.class);
intent.putExtra(key,value);
startActivity(intent);
And in your SecondActivity, you can always retrieve that data like this:
Bundle bundle = getIntent().getExtras();
if ( bundle != null && bundle.containsKey(key) ) {
value = bundle.getInt(key); // not nessecarily getInt(), you should use according to your value type
// use the value to tell if it is from your own app
} else {
// it is not from your own app
}
You can use this mechanism combined with the lifecycle methods. For example, if you use the latter code in your onCreate() method, then whenever the Activity is created, if will check who creates it, which sounds like your what you might want.
As soon as your activity becomes visible it will call OnStart() and as soon as it is ready for the interaction(such as touch ,click etc event). it calls onResume, at this stage your app is running and it is completely in foreground. When your activity start another activity or a dialog box then it calls onPause it means activity is visible but user can not interact with the Activity UI. in case we start another Activity which completely hides the previous activity then its onStop method is called
onPause: Called when another activity comes into the foreground.
onStop: Called when that other activity is completely visible.
onResume: Called when your activity is navigated back to from the onPause state.
Maybe your app was already in the onStop state, so then it would call onRestart.

android finish current activity causes app close

I am executing maswebview class and I would like to finish only this activity. I tried maswebview.this.finish() but when executed, app is been closed. Then if I set a new view for the tab content, it is loaded properly and webviewmas dissapears but just for a while, then appears again fitting fullscreen. How to finish maswebview completely? ThanK you
public void onClick(View arg0)
{
/*
Intent intent = getIntent();
intent.addFlags(Intent.FLAG_ACTIVITY_TASK_ON_HOME);
startActivityForResult(intent, 1);
Intent intentmas = new Intent (maswebview.this, mas.class);
intentmas.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
intentmas.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intentmas.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intentmas.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
View vista = getLocalActivityManager().startActivity("maswb", intentmas).getDecorView();
setContentView(vista); */
maswebview.this.finish();
Do you have any other activities of your app in the stack by the time you call finish()? If you don't, you'll want to start the desired activity instead of finishing the current one.
But actually it seems to me that you're trying to accomplish something that can be done simpler. Can you provide more info on the task at hand and your app structure you're trying to go about it with?
From what you said, it seems like you have tabbed UI and you're trying to show a webview in one of the tabs, then hide it.
First, I don't see why you want the webview in a separate activity. Seems to me you could just have it in layout of one of the tabs and just call setVisibility(GONE) to hide it.
Second - and this is important - looks like you're trying to implement tabs the old way - TabWidget, TabHost, etc. Since Honeycomb has been released, there's much more convenient way to implement tabbed UI - Action Bar Tabs and Fragments - that approach is much more convenient and will render your webview problems obsolete: there's a thing called WebViewFragment which is basically a WebView but smarter - it will handle its own lifecycle with minimum effort required from you (i.e. pause when removed, resume when added). It will take some effort to study up on Fragments, but it's well worth it. You can get Fragments API for pre-Honeycomb android sdks as a static library - it's called android-support-v4 and you can download it in Android SDK Manager.
Are you calling "maswebview.this.finish();" before the new Activity is started?
Also if you want to just start this new activity without having the old activity in existence then you can add android:nohistory="true" to your manifest.xml. This will cause the current activity to be the only activity in the queue.
See HERE
You need to provide a little more information for us to better understand what exactly is going on.
I hope this helps.
Try following code
#Override
public void onBackPressed() {
if(childView != null && parentLayout.getChildCount()==2){
childView.stopLoading();
parentLayout.removeViewAt(parentLayout.getChildCount()-1);
if(webView.getVisibility() == View.GONE)
webView.setVisibility(View.VISIBLE);
}else{
super.onBackPressed();
}
Do you have a parent activity which is launching this one? If yes make sure you don't call finish() after launching maswebview, that way the parent activity will remain in the stack. Once maswebview would exit, onResume would be called for your parent activity.

Prevent background Activity from being killed?

I have an app that has a list of menu items. When you click a menu item it opens a corresponding activity. Now in that new activity when you click the back button and return to the main list, that activity gets killed and it does not return to its past state when you start it again.
My question is, is it possible to not kill the activity when you leave it?
I tried saving values like so:
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString("TO_REMEMBER", "Remember this");
}
However once the activity gets killed and than re-started, the oncreate method is not reading any data:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null) {
//This is not getting fired
Toast.makeText(this, savedInstanceState.getString("TO_REMEMBER"), Toast.LENGTH_LONG).show();
}
}
Any help on this is appreciated.
Your are saving state using onSaveInstanceState but that is not meant to save state across activity life-cycle when you press back. That is meant to save state across orientation changes etc. That needs to be done if you want to save some state across orientation change, so you are right there.
Now to save something across activity life-cycles, you have two options:
One, save your state to a persistent DB or something.
Second, if it is not to be stored in DB, then use getPreferences and store it using this. This will store it for that specific Activity only. I ll recommend this if you are trying to store the state of activity.
Edit:
Well leaving Activity alive is not a recommended/documented approach. You can have Service running in the background but does not contain UI as Activity does. If you press Home button instead of Back then it will act something like orientation change.
In short, Activity is responsible for saving its state. That said, some UI controls save their state themselves so you dont have to save their state example EditText will save its state.
Ref:
getPreferences
Shared Storage
Saving Activity State
If you are new to android, you should start with the dev guide which is a really usefull Tutorial for starters which is found here.
As for the BackStack, you can check it here.

Android - Show last viewed Activity When press (Home Button-->App Shortcut)

I came to do the eternal question, which so far have not found a solution, I searched on the internet the same problem but found a final solution to this problem.
when I have 2 activities open and I pull the 'Home Button' and then press the shortcut for my application, it shows me again the first activity (the launcher activity), and then to return to the activity that was displayed, I have to press the back button.
what is the solution to this problem?
I want to press the shortcut of my application (after having left my application by pressing the Home Button) show me the last activity was displayed, instead it shows me the first activity (activity launcher).
Thanks in advance.
That is the expected behavior. The launcher will launch the Activity with the filter android.intent.action.MAIN.
There are ways to work around it, though. A very simple one is to have a boolean flag mRunning that you will set to true upon launch. If true, then on the onStart() method you start an intent to launch your second Activity; if false, then go on with setContentView().
If you have several activities to go back to, then a feasible approach is to save the current activity in SharedPreferences and launch it the same way.
Alternatively, your main Activity may be just an entry Activity whose only job is to start the last Activity used.
EDIT: I found this duplicate question: How to make an android app return to the last open activity when relaunched? that has a much better ansewr than mine.
Your application is still running in the background when you press the home button. finish() the activity when you press the Home button if you want to go back.
Depending on whether or not your main activity is ever launched by another activity, or only the application icon, you can use a much simpler solution. If your main activity is only launched by the application icon, you can use isTaskRoot() to check if your main activity is being launched as a fresh start to the application, or if the user is returning and the main activity is being laid on top of other activities that you wish to display instead.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (! isTaskRoot()) {
finish();
} else {
...
}
}
You can use startActivityForResult replace for startActivity when you want to open another Activity.

Categories

Resources