I am using Navigation library and my use case is preserve Fragment state on back press which I achieve by returning already inflated binding in onViewCreated as when changing fragments Navigations seems not to destroy already existing instance of this fragment the actual view variable exists when you navigate there back or up.
But I also have a use case when I need to recreate this Fragment instance so I expect to have a way to call onDestroy() for that fragment. But I don't see any api for removing/obtaining existing in the backstack instances.
So my question is how to get an existing instance of a Fragment from nav back stack and destroy it or just remove it by calling nav controller api.
some code:
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
viewModel = ViewModelProviders.of(requireActivity(), mViewModelFactory)
.get(MainViewModel::class.java)
parseNavigationExtra()
return if (::mBinding.isInitialized) {
mBinding.root
} else {
//create new binding
}
so when I call this action I still get the old binding root as the variable is still present.
<action
android:id="#+id/clearBackStack"
app:destination="#+id/mainFragment"
app:launchSingleTop="true"
app:popUpTo="#+id/mobile_navigation"
app:popUpToInclusive="true" />
List<Fragment> fragments = getActivity().getSupportFragmentManager().getFragments();
Fragment lastFragment = fragments.get(fragments.size() - 1);
getActivity().getSupportFragmentManager().beginTransaction().remove(emptyDialog);
changes in the navigation library since 2.1.0
NavBackStackEntry: You can now call NavController.getBackStackEntry(), passing in the ID of a destination or navigation graph on the back stack. The returned NavBackStackEntry provides a Navigation-driven LifecycleOwner, ViewModelStoreOwner (the same returned by NavController.getViewModelStoreOwner()), and SavedStateRegistryOwner, in addition to providing the arguments used to start that destination.
So the plan is to use the new api to see what is available for NavBackStackEntry.
Related
Working on an Android app where each user can have multiple accounts under the same login. There is a single activity with a fragment per tab - based on the Android sample Bottom Navigation.
On one of the tabs is a calendar, which is hooked up to a ViewModel like so:
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
val calendarViewModel = ViewModelProvider(this).get(CalendarViewModel::class.java)
calendarViewModel.calendarEvents.observe(viewLifecycleOwner) {
// Code that modifies the UI to show the events on a given day
}
val progressBar: ProgressBar = binding.progressBar
calendarViewModel.calendarState.observe(viewLifecycleOwner) {
// Progress bar / error state handling code
}
}
On one of the other fragments (different tab in the bottom tab bar), I allow the user to switch accounts. When I come back to the calendar fragment/tab, the viewModel is still in scope so I have incorrect data for this user.
How can I manually force the ViewModelProvider to recreate the viewModel in onCreateView? Is there some way I can invalidate the ViewModel scope and force a re-pull of the data?
Scenario: I have 2 fragments ProductList and ProductDetail in my nav graph. And when i click on any product it opens the ProductDetail fragment using findNavController.navigate() method.
Problem: The problem is when I go back from ProductDetail to ProductList fragment, the ProductList fragment reloads again and it also calls the api to fetch products list, which I want to avoid.
If anyone knows the reason behind it or the solution to this particular issue please let me know in comments.
You should cache the fetch result locally, pull from the cache either during a fetch attempt or upon failure of a fetch attempt. This is a very common pattern on mobile.
Finally I got the answer from somewhere, so I am posting the sample code to resolve the issue I am facing -
private lateinit var contentView: View
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
if (!::contentView.isInitialized) {
binding = FragmentNewProductListBinding.inflate(layoutInflater)
contentView = binding.root
// initialize your views or set click listeners or call apis
}
return contentView
}
Note: To elaborate, there is some internal bug in the navigation library where it draws the previous fragment from scratch when going back from another fragment. So as a workaround or temporary patch, what we can do is just check whether the view is already initialized or not, if yes then don't create it again.
Hope you understand the reasoning and answer.
When nav component switches to a fragment, I get this "Views added to a FragmentContainerView must be associated with a Fragment" crash. What causes this?
I didn't see this mentioned anywhere and it took a while to figure out but in this case, I was trying to set up a old legacy fragment while migrating to the nav arch component.
The reason was in the frag's onCreateView, the inflate looked like:
layoutView = inflater.inflate( R.layout.home, container, false );
The last argument automatically attaches the view to the container. This works fine in old style fragments and activities. It does not work with the nav arch component because the root container is a FragmentContainerView which only allows fragments to be attached to it.
Setting the last argument to false makes it work properly.
Just replace your onViewCreated method.
class MyFragment : Fragment() {
override fun onCreateView( inflater: LayoutInflater,container: ViewGroup?, savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_post,container,false)
}
}
If you are working with lifeCycleScope, make sure you launch and run the block at least in Lifecycle.State.STARTED state.
I'm using a shared ViewModel in Navigation component rather than creating a ViewModel for every fragment (mostly because it's easier) but now I have a problem when I re-enter a fragment and subscribe to the ViewModel live data of that fragment, I get the last state also too.
here is the ViewModel Code:
val apiLessonData: MutableLiveData<String>> = MutableLiveData()
fun getLessonsUserCreated() =
apiCall(MyMaybeObserver(apiLessonData))
in MyMaybeObserver, I have somthing like this:
override fun onSuccess(t: T) {
apiDataObserver.postValue(t)
}
and this is how I observe it in my fragment:
private val apiAddGoalData = Observer<String> { response ->
showSnack(response)
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
.
.
viewModel.apiAddGoalData.observe(viewLifecycleOwner, apiAddGoalData)
.
.
}
now when I enter the first time it works fine but I open it the second time, it shows the snack from the previous time, how to stop this without creating new ViewModel?
In the simple way You could set null for your MutableLiveData after getting data in onchange method of the observer. For more information you can read this article:livedata-with-snackbar-navigation-and-other-events-the-singleliveevent-case
. also you can see this question maybe help you: How to clear LiveData stored value?
I don't think your problem is with the LiveData since you are wisely using the viewLifecycleOwner, problem is with the state of the view and lifeCycle of the fragment. With navigation component of jetpack, fragments get replaced in the container. Think of this scenario: You open fragment A then you navigate to frament B and press back button to return to fragment A. onCreateView and onViewCreated methods of the fragment A gets called again. Since the onDestroy of fragment A haven't been called when you opened fragment B some of the view states will be restored while returning to A. This is as you might know the same reason we use viewLifecycleOwner. So Nullify or clear the state of the views in the onDestroyView of the fragment A:
recyclerView.setAdapter(null)
checkBox.setChecked(false)
I have been trying out Navigation Component for a while now but somehow not getting the reason (or explanation) behind current Lifecycle of Navigation Component. Here are some points that needs clarification.
1. Fragment to Fragment flow
In navigation Component every fragment (or lets say page) is recreated every time it is visited (or revisited). So, when you are at A and go to B, A is destroyed and later when you go back to A (like pressing back button) A is created from stretch.
In a traditional Activity patterns when you go back to A it just goes to onResume as it wasn't destroyed when moving to B. Any reason that this pattern is changed in Navigation Component?
The problem of recreating is when you have a lot of data and it takes time to get redrawn and it feels like app is freezing. An example would be simple HomePage (say Facebook NewsFeed). Preserving data can be handled with ViewModel but drawing of all of the feeds again require time and it will freeze.
There is another problem that recreation generates. Assume this scenario: A has an Collapsing AppBar with a NestedScrollView. User scrolls down and AppBar will collapse and then user moves to a different page B. When he comes back to A it will be redrawn and AppBar is expanded. I am not sure if it is a bug or I should do something to fix it? So any solution here is also welcomed.
2. Activity recreation
If activity is recreated for certain reasons like orientation change, every page in Navigation Component gets recreated until current destination. Although onCreate method of Fragment not onCreateView is getting called, I don't see a point of creating Fragments in Activity recreation. Any explanation would be welcomed.
Navigation component only supports fragment replacement as of now. So you won't be able to add() a fragment as you do it with Manual fragment transaction.
However, if your worry is about re-inflating the layout and re-fetching the data for the fragment, it could be easily resolved with below two methods.
Once the view is created, store it in a variable and use it whenever onCreateView() is called.
private var view: View? = null
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
if (view == null) {
view = inflater.inflate(R.layout.fragment_list, container, false)
//...
}
return view
}
Source: https://twitter.com/ianhlake/status/1103522856535638016
Use ViewModel with the Fragment and hold the data required as a member variable. By this way, the data is not cleared when you replace the associated fragment. The ViewModel gets cleared only on onDestroy() of the fragment, which will only happen when you destroy the parent activity. https://developer.android.com/images/topic/libraries/architecture/viewmodel-lifecycle.png
The way that we use fragments to bridge data and views has changed slightly, and in a good way, when migrating to the Navigation library. It forces us to distinguish between Fragment and View lifecycles.
Pre-navigation: observe LiveData in onCreate() using Fragment's lifecycleScope.
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
...
import kotlinx.android.synthetic.main.old_fragment.*
class OldFragment : Fragment(R.layout.old_fragment) {
private val vm by activityViewModels<MainViewModel>()
override fun onCreate(savedInstanceState: Bundle?) {
vm.getLiveData().observe(this) { data ->
oldTextView.text = data.name
}
}
}
Navigation: observe LiveData in onViewCreated() using viewLifecycleOwner scope.
...
class NewFragment : Fragment() {
private val vm by activityViewModels<MainViewModel>()
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
vm.getLiveData().observe(viewLifecycleOwner) { data ->
oldTextView.text = data.name
}
}
}
Key Notes:
Not all Lifecycle Owners are the same. The fragment lifecycle will not execute the observer when the view is recreated (while using Navigation library and navigating up/back).
The viewLifecycleOwner cannot be accessed before the view is created.
Hopefully, this can help prevent replacement of LiveData code as developers migrate to Navigation.