How to know when an Activity dies in a Fragment - java

I have a fragment that is being loaded by an Activity.
I know things such as
onPause()
onStop()
On stop gets called too late and sometimes not at all.
But my Activity dies I want to know so that I can tell my fragment to clean up.
What is the fastest way?

I'm not realyl sure what your question is, but perhaps you will find this useful.
https://developer.android.com/guide/components/fragments.html#Creating
I suggest reading up on the fragment life-cycle

onDestroy() will be called just before the Fragment is destroyed. This could happen because the parent Activity is also destroyed or because the Fragment is no longer displayed.

Related

Why do codes work in the onCreate() instead of onResume()

I'm like an intermediate in android programming. I decided to take a deep dive into the Activity lifecycle methods and I realised something, like why do methods Toasts.show() and many other methods get called again when the activity is resumed. If the methods are in the onCreate so why then if you like go to another activity and return it will still give you a Toast message. Let me give an example.
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
{Your Initialization go here }
//Toas message
Toast.makeText(code).show();
}
}
So imagine you leaving this activity for another one and then coming back... why does it still show the Toast message. Because since the lifecycle is
OnCreate
onResume
onStart
onPause
onstop
onDestroy
And when you come back to your MainActivity it calls the
onResume
onStart.
So if onCreate is not called...So how does the Toast message show.
Please someone should help me answer this I've searched all day but couldn't find answers.
accoording to lifecycle of activity https://developer.android.com/guide/components/activities/activity-lifecycle, if there is no memory engouh the app process will kill, so when you back to your activity on created will call another time.
the image below for clarification:
When your activity goes in the background, and memory is required for other apps. It is possible that the system frees up space even though your activity is in the background with ONPAUSED state. and now if you navigate to your activity, since the saved instance is removed due to memory requirements. instead of ONRESUME, ONSTART is called. you can read more about it here: https://developer.android.com/guide/components/activities/activity-lifecycle
and see this image for better understanding: https://developer.android.com/guide/components/images/activity_lifecycle.png
This uncertainty is one of the reasons why we now mostly use view models for a sizeable app.

When I rotate the screen, the fragment is destroyed and returned to Activity, which opened that Fragment. But why he's doing so?

I have an Activity which can open 2 different Fragments by 2 different Buttons. By the default that Activity when it creates, it is opening a Fragment, we call it "The Main Fragment".
The first Fragment to which we are going over by the first Button we meet zero problems with the Rotation, but the second one after the rotation disappears and the screen shows the Main Fragment's content. When I tried to rotate the screen back, I see the Main Fragment's content again. But why it is so, if I didn't write any code, which must return me to the Main Fragment without clicking a button.
What assumptions do you have?
Why this is happening ?
Default Behavior, Actiivty is getting recreated on orientation change so your fragment are.
Explanation
You need to understand Activity Life Cycle to understand why this is happening.
First, “rotating the screen” is not the actual scenario we are talking about today. Because any configuration change will cause Android to restart your Activity. A configuration change might be the device rotating (because now we have a different screen layout to draw upon), or it could be a language switch (because we need to re-write all those strings, which may need more room now OR it could be the scary RTL switch!), or even keyboard availability.
By reloading your app, what the system is actually doing is calling onDestroy() and then immediately calling onCreate(). This way, your Activity is as fresh as possible, with all of the right creation data (even though the user has been with you the entire time).
Now you have following option -
Either Fix Orientation for your app from AndroidManifest.xml
But oviously that is not a very good experience for user.
Save activityState with onSaveInstanceState()
This method will be called before onDestroy(). And, when your Activity is created, there’s a matching step onRestoreInstanceState(), which will also be called automatically. All of these automatic steps mean that you can let the system worry about saving and loading your data, because you planned ahead and mapped out what was important. (Or, you can skip onRestoreInstanceState() and load your saved state from the Bundle that comes with onCreate().
In you integrate Fragment in activity, because activity is getting destroy() so your fragment will also destroy() and will be recreated.
Please take a good read on Handling Configuration Change and this.
Once you understood the concepts things will start falling into your but it will only happen if you will complete your learning curve.
Happy Coding !
That is because onCreate is being called every time the screen is rotated. Probably you are displaying The Main Fragment from your onCreate method. You will face the same issue if you put your fragment display logic in onResume because just after onCreate, onResume is called.
Solution: store the fragment on top in shared preferences that way you know what to display every time onCreate is being called.

How to run code when app is re-entered after going to home (Android)

I want to run some code after I hit my home button and the re-open the app. How do I run code when the app is re-opened (Not After Being Killed) in android-studio?
you can use onStop() method or onDestroy() , if you will close totally that Activity use onDestroy() and if you just will put it in background you can use onStop()
Doc for onDestroy()
Perform any final cleanup before an activity is destroyed. This can
happen either because the activity is finishing (someone called
finish() on it, or because the system is temporarily destroying this
instance of the activity to save space. You can distinguish between
these two scenarios with the isFinishing() method.
Doc for onStop()
Called when you are no longer visible to the user. You will next
receive either onRestart(), onDestroy(), or nothing, depending on
later user activity.
i saw you edited your question, look at the lifecycle
Like sagar says, you can use onResume() in order to recover your current Activity
You can perform the action in onResume() method. This is the state in which the app interacts with the user. The app stays in this state until something happens to take focus away from the app. Do note that there is no differentiation between Activity coming from background to foreground or Activity created from scratch. onResume() will be called whenever app enters foreground state.
In order to differentiate it in onResume() you need to maintain a boolean flag. You can set the flag in onStop() and check it in onResume().
This approach will only work, if the OS hasn't killed the process, hosting your Activity, due to memory constraints. In this case your Activity will be recreated.
You can use onRestart() since when you left your activity to go home it goes into onStop() and after that when you launch it system will call onRestart() the onStart().
for more info refer following ans:
https://stackoverflow.com/a/35476531/7271231

Android: When to end class with finish()?

I often see examples of classes which end with finish(), but definitely not always. My question is when should you end a class with finish()? And what does it do exactly, what is the difference between ending a class with the back button and ending it with finish()?
Thanks in advance!
finish() can be called to kill (destroy) an Activity instance. If you don't need to close your Activity manual, which is true in many cases, you don't need to call this method.
But if you require a button somewhere in your activity that says "close", then you should use this method. But in general the back button behavior in Android will handle things like this.
The back button does not actually finish your activity, finish() calls the onDestory() method right away, while the back button does not.
When the back button is pressed, the onStop() method is called, but the onDestory() method call might be delayed by the system, this so that the Activity can be resumed by the system which is cheaper (in resources) than a full restart.
Lifecycle:
http://developer.android.com/reference/android/app/Activity.html#ActivityLifecycle
Finish():
http://developer.android.com/reference/android/app/Activity.html#finish()
You finish Activity class with finish() method when you need to end the Activity immediatly at specific point. If you press back button, you will go through the lifecycle (onPause(), onStop() then onDestroy()) automatically.
One reason to use finish is when you have started the activity with
void android.app.Activity.startActivityForResult(Intent intent, int requestCode)
In this case you dont go back to the Activity which started it with another startActivity but with finish
Back button takes you to the last activity in the stack whereas finish() destroys the current activity. You can call finish() on an activity for which you don't want the user return to. Example: LoginActivity
public void finish ()
Call this when your activity is done and should be
closed. The ActivityResult is propagated back to whoever launched you
via onActivityResult().
finish() is called to kill your activity instance after you did what you have to do with the activity. After that, you have no use with the activity. So simply call finish() and it will kill your activity.
If you press back button, it will call finish() automatically to kill the activity. It will go through the activity lifecycle(onPause(), onStop() and finally onDestroy())
The one reason with calling finish() is that, if you don't call it, when you navigate through activities, all the activities will be added to the backstack. So when you go back, you have to come back through these activities. So for e.g when you click back button, it simply kills the activity and it will be removed from the backstack.

Advice on onPause and onResume

If i use the code below will this restore text that has been input into EditTextfields and selected spinner items?
#Override
protected void onPause(){
super.onPause();
}
#Override
protected void onResume(){
super.onResume();
}
or do I have to tell it to save the current values and then restore then when activity is resumed? when I am using the emulator if I don't have these methods in and I go to say home then run my app again it always loads back to the previous state, so my questions is does this actually do antyhing?
Nope, this actually only called the super class onPause() and onResume() without doing anything else. The value in your editbox stay there because even if the app is paused, is still there on the activity stack waiting.
However Android can kill your paused activity and your data will be lost. So you have to save them onPause and restore them on the onResume to avoid this.
No, this code does not do anything. You're overriding these methods, but giving them an implementation of just calling the parent implementation. This is the same as not overriding them in the first place.
It's not absolutely necessary to save/restore state for when you pause/resume. The only reason why you would need to manually do some state saving is if you want to restore state even after your application is killed.
You values still the same in your spinner because the app hasn't been kill yet. It's only put a pause state still in memory. If the app were destroyed the values of your spinner will be back to the onCreate method and whatever value they had at the start.
Look here for what each method does --> https://developer.android.com/reference/android/app/Activity.html
You only need to save state when onDestroy() is called. That only happens when you use the back button or the OS kills the Activity when it is in a stopped state.
If you Activity becomes partially obscured it will be paused but if it is completely obscured it will be stopped.
When it is top of the stack again it will resume or start.
To experiment use Log to write messages to the LogCat when each of events occurs and then you will be able to see when and why they are called.

Categories

Resources