Scenario:
I have a single Activity in which I have multiple fragments and I'm replacing one fragment with another using fragment transaction and add them to BackStack. I am doing JSON parsing and network related task on some fragments.
Problem:
My problem is that after replacing the fragment when I press back button to nevigate to last fragment the onStart and onActivityCreated methods called again. My code in these events execute each time I navigate to that fragment by using back button
But
Any value in EditText remain same in even after replacing the fragment and coming back to it using back button.
Why onStart and onActivityCreated executed each time?
Is there any method where I can put my code which do not execute after coming back to fragment?
UPDATE
Basically I want to set a button text once fragment is created. User can change that text. but when I return back to that fragment the users value change with the default text which I set on fragment creation time.
Thanks
You can put your code to run only one time at fragment creation in onCreate() of fragment..
onCreate()
The system calls this when creating the fragment. Within your implementation, you should initialize essential components of the fragment that you want to retain when the fragment is paused or stopped, then resumed.
See the life cycle of fragment.
You can also get more details here
Related
I have FragmentX in a ViewPager. FragmentX has EditText's in it and a Button. The user presses the Button and FragmentY replaces FragmentX. The user then presses back and FragmentX has lost all of its input from the user.
How do you either:
a) Save the data in FragmentX before FragmentY appears then FragmentY is replaced by FragmentX retrieve the data and fill in the EditText's in FragmentX
(please don't reply with OnSaveInstanceState, as this does not work unless the Fragment is destroyed, which in this case it is not)
b) somehow keep the data in FragmentX so it is there when we go back to FragmentX from FragmentY..
Any suggestions?
Using addToBackStack() might help in your case.
If you return to a fragment from the back stack it does not re-create the fragment but re-uses the same instance and starts with onCreateView() in the fragment lifecycle, see Fragment lifecycle.
So if you want to store state you should use instance variables and not rely on onSaveInstanceState().
Check this out: Maintaining fragment states
I am now saving the data in FragmentX to SharedPreferences and overriding onBackPressed in the Activity, and have created a function in the Activity called popFromBackstack where the popBackStack() occurs.
In the functions in my Activity where i replace my Fragments i am now saving the data in FragmentX into SharedPrefs before the replace. I am also checking after the replace if the new Fragment is FragmentX and, if it is, i am filling the data into FragmentX from SharedPrefs.
I am also saving the data from FragmentX in onBackPressed in my Activity (if the current fragment is FragmentX), incase the user presses the back button.
I have also created a public static activity called popBackStack() in my Activity which i call from Fragments to pop the backstack. I am also saving the data from FragmentX here (if the current fragment being popped is FragmentX). Once the Fragment being popped is popped i am checking if the new Fragment is FragmentX, and filling in the data if it is...
Long winded approach but i couldn't figure out any other reliable way. This is working perfectly.
I suggest following guidelines that Google provides and implement an interface declared in your Fragment and save the Bundle or whatever object you want in the activity. Then, in your newInstace() static factory method pass that Bundle and recreate data as usual. Since you are using a ViewPager and it will always render the second fragment before the button is pushed (I assume your second fragment is in another tab) you still need to manage it via an interface. When the back button is pressed, the data will still be there, unless it is destroyed, and you still need to implement onSaveInstaceState() for that matter. You can also use setRetainInstance(boolean retain). See here for more details
I have a scenario where I have 2 fragments.
Clicking on a button in the first fragment takes you to the 2nd fragment.
By clicking the "UP" button in the 2nd fragment you'll get navigated back to the first fragment. Unfortunately the OnCreateView() method of the first fragment is not called.
Is there a way to call it? Which methods are called by clicking the "up" button?
It won't be called since 1st fragment is not yet detached from its activity and not destroyed yet. In your case, onResume() callback would be the best place to put your code.
OnCreateView doesnt get called because the fragment A is already created.
Read about the Fragmetn/Activity lifecycle and u will understand that.
OnResume will get called once pressed back from Fragment B, so u can put your logic in that method.
Imagine the following scenario:
Push Fragment A onto BackStack
Push Fragment B onto BackStack
Push Fragment C onto BackStack
Fragment B tries to make a async web request when its onResume is method is called.
Fragment C has a button called "Clear Backstack" that clears the backstack by calling popBackStackImmediate(null, FragmentManager.POP_BACK_STACK_INCLUSIVE).
When PopBackStackImmediate is called it pops the Fragments off one by one until the stack is cleared. As each fragment is popped the fragment's onResume method is called. For Fragment B, I don't want the async web request to trigger since its going to be immediately destroyed/removed after its popped (because the entire backstack is being cleared).
In this case how can I detect if the entire backstack is being collapsed and skip the async web request on Fragment B in the OnResume method? Note: I'd still want the async web request to execute if Fragment B is popped/displayed by using the Back button.
Note: I'm using the latest compatibility/support library.
Option 1:
Have you determined what other lifecycle methods are being called - if it's only on resume, then move the async call further down in the lifecyle (onCreateView or onAttach for example) so that it's only called when moving through it in the normal manner.
Option 2:
When onResume is called you could do a getFragmentByTag on the fragment which has already been destroyed. If this is null you could then assume that the operation in action is the destruction.
This one seems pretty ugly to me.
Option 3:
Have C pass some flag up to the controlling activity (we'll call it Main), move the async call up, and when B wants to do the web request, have it call up to main to do so. If C has set the "I'm Destroying" flag, then don't perform the request.
Update: I was previously removing the old fragment and then adding the new fragment using FragmentTransaction.remove and FragmentTransaction.add respectively. Switching to FragmentTransaction.replace solved most of my problems when working with the backstack. See below:
The Android documentation has this to say about FragmentTransaction.replace:
Replace an existing fragment that was added to a container. This is essentially the same as calling remove(Fragment) for all currently added fragments that were added with the same containerViewId and then add(int, Fragment, String) with the same arguments given here.
I found the documentation to be slightly misleading because there is an important difference between replace vs. remove+add when the backstack is involved:
If the backstack A->B->C is built using remove+add, then popped back to fragment A, then fragment B's onResume method will be triggered.
If the backstack A->B->C is build using replace, then popped back to fragment A, then fragment B's onResume method will NOT be triggered.
I'm trying to understand some odd behavior. I have an ActivityA that calls a method in onCreate() to add FragmentA to R.id.fragment_container. Inside FragmentA I have a button that attaches FragmentB by using ActivityA's fragment manager (getActivity().getSupportFragmentManager()) and replacing the R.id.fragment_container and I also add it to the backstack. I also have another button that starts a new ActivityB.
When I navigate back from ActivityB I get: ActivityA onResume(), FragmentA onResume(). But when I navigate back from FragmentB I get: FragmentB onCreateView(), FragmentB onActivityCreated() then the 2 onResume().
So my questions is...why is the view state saved when a new activity is launched and not when the fragment is replaced and reattached. It looks much better to just restore that state rather than recreate the views and fetch that data again. This seems like opposite behavior from what I would expect so I'm clearly missing some fragment state saving/restoration step or something. It seems like the activity is just pausing FragmentA (and ActivityA) when ActivityB is launched and restoring it on back pressed but when FragmentB is attached FragmentA gets completely destroyed. I'm sure there's a way to prevent this I just can't seem to figure it out. Thoughts?
Just below your question are four tags android,android-fragments,android-lifecycle& android-navigation .Put your cursor over it for a while a black box will pop up . click on info tab and you will get best links to study that topics along with links to books .
Hope this will help you
I'm trying to implement List->Detail scheme with details pagination.
I've single Activity for ListView and different Activity with ViewPager.
In FragmentStatePagerAdapter.getItem i instatniate new fragment for page and pass item id via setArguments Bundle.
After opening pager Activity two Fragment pages are created and onCreate, onCreateView, onActivityCreated being called.
BUT
onLoadFinished is called only for first Fragment (currently visible).
If i go back onLoadFinished is called for second Fragment.
Strage thing is that when i swipe to second (onLoadFinished for third not called), back to first and again go forward to second OnLoadFinished is called for third fragment and every next - after going back and forward always next fragment is being fully created in advance.
Is this bug or feature?
How fully loading can be forced?
We've solved this by manually calling onStart and onResume in onCreate.. Then onLoadFinished is called