In my activity I use three buttons at bottom to choose between fragments like this for example:
scenarioFragment = new ScenarioFragment();
android.app.FragmentManager fragmentManager = this.getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.fragment, scenarioFragment, scenarioFragment.toString());
fragmentTransaction.addToBackStack("stack");
fragmentTransaction.commit();
so in ScenarioFragment, I bounded a connection to my service.and whenever I change between fragments a new fragment is created and I have to bind a new connection.
I want to save all fragments state and restore it as they choose.
thanks.
According to what you said, your Fragment have the same Activity as a parent.
Assuming this, you could create a ViewModel (Component introduced as part of the Android Architecture Components) for your activity and put whichever state you want in them.
Then, inside each of your Fragments you can get the ViewModel with the statement:
ViewModelProviders.of(getActivity()).get(ViewModelClassName.class);
The key to this statement is to make sure you pass in the getActivity so that you can get the same ViewModel instance in all the Fragments as long as they are attached to the same parent. If you pass the Fragment instead of the Activity like this ViewModelProviders.of(this).get(ViewModelClassName.class); you will have a new instance of the ViewModel tied to the scope of the Fragment that will be cleared if the Fragment is destroyed.
This is possible because the ViewModel class will be created using the scope of the Activity and it doesn't matter how many time you recreate your fragment you will be getting the same ViewModel instance with your state.
You can learn more about Android Architecture components here.
If you wish to understand a bit more about how the ViewModel works internally you can find out more on a post I wrote here.
Related
framentA calls fragmentB via an mother activity. FragmentA is no longer in memory. FragmentB calls fragmentA(go back to previous screen). FragmentB has some data to share with FragmentA. But, how?
here is what I tried:
static variable - it worked, but a bad habit, I can not use it
viewModel - each fragment creates it's OWN instance of view model. Therefore the 2 instances of the viewModel will not work.
DB - not a good pattern. Therefore I cant use it.
I think what you need is to store the fragments in Fragment Manager, when you do that you are basically trying to maintain a back stack of your fragments:
FragmentManager fragmentManager = getSupportFragmentManager();
//or FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.add(FragmentToBeAdded, "textRelatedtoFragment")
.addToBackStack(null)
.commit();
Adding to the backstack helps in saving the state of the fragment.
My suggestion would be:
For Fragment Navigation use: https://developer.android.com/guide/navigation/navigation-getting-started
It will greatly simplify your in-app navigation.
For passing parameters between Fragments/Activities:
First solution is to use ViewModel with scoping of Activity using by activityViewModels(). Read More here: https://developer.android.com/jetpack/guide This will give you an indirect way of passing arguments.
Use SafeArgs (part of Navigation component) to directly pass needed data.
More information can be found here: https://developer.android.com/guide/navigation/navigation-getting-started#ensure_type-safety_by_using_safe_args
That is what I have in my app
Activity with 2 fragment with ViewModels and Databinding.
Room Database with Livedata to update UI continuously.
Navigation Controller to navigate between fragments.
Fragment #1 have RecyclerView (List of Custom Object).
Fragment #2 is to Insert or Update operations (Transactions).
Everything works fine as expected, but one thing I can't figure out why it happens.
When I go to Fragment #2 to Insert or Update data to Room Database then back to Fragment #1 with (top or bottom) back button, fragment #1 doesn't reload and data doesn't change (update) until I reload data.
In other case when I Insert or Update data at the same fragment the list changes immediately.
Do I have to make insert and update operations at the same fragment?
Can't I do it at other fragments and when I go back to the list fragment I find that data is been updated?
Keep in mind that it was work like I hope but at some point i really don't know it doesn't any more !!
After searching, the problem was that I was create instance from repository which contain ROOM database DAO, So all LIVEDATA connections to the database was removed
The solution was to use singleton pattern, which mean to use only one repository instance and one room database instance during the full lifecycle of the activity which contain my fragments.
You can do this many ways, I recommend you to use Dependences Injection
Tool I used was HILT DAGGER here here
Create a function in class where fragments are defined like this.
public void refresh( ) {
fragment = new ListFragment();
fm = getSupportFragmentManager();
ft = fm.beginTransaction();
if (fragment != null) {
FragmentManager fm = getSupportFragmentManager();
fm.beginTransaction().replace(R.id.container, fragment).commit();
}
}
Now Call that in your 2nd fragment where you want to call 1st fragment after any action.
((MainActivity) Objects.requireNonNull(getActivity())).refresh();
While Navigation component of JetPack looks pretty promising I got to a place where I could not find a way to implement something I wanted.
Let's take a look at a sample app screen:
The app has one main activity, a top toolbar, a bottom toolbar with fab attached.
There are 2 challenges that I am facing and I want to make them the right way.
1. I need to implement fragment transactions in order to allow replacing the fragment on the screen, based on the user interaction.
There are three ways I can think of and have this implemented:
the callbacks way. Having a interface onFragmentAction callback in fragment and have activity implement it. So basically when user presses a button in FragmentA I can call onFragmentAction with params so the activity will trigger and start for example transaction to replace it with FragmentB
implement Navigation component from JetPack. While I've tried it and seems pretty straightforward, I had a problem by not being able to retrieve the current fragment.
Use a shared ViewModel between fragment and activity, update it from the fragment and observe it in the activity. This would be a "replacement" of the callbacks
2. Since the FAB is in the parent activity, when pressed, I need to be able to interact with the current visible fragment and do an action. For instance, add a new item in a recyclerview inside the fragment. So basically a way to communicate between the activity and fragment
There are two ways I can think of how to make this
If not using Navigation then I can use findFragmentById and retrieve the current fragment and run a public method to trigger the action.
Using a shared 'ViewMode' between fragment and activity, update it from activity and observe it in the fragment.
So, as you can see, the recommended way to do navigation would be to use the new 'Navigation' architecture component, however, at the moment it lacks a way to retrieve the current fragment instance so I don't know how to communicate between the activity and fragment.
This could be achieved with shared ViewModel but here I have a missing piece: I understand that fragment to fragment communication can be made with a shared ViewModel. I think that this makes sense when the fragments have something in common for this, like a Master/Detail scenarion and sharing the same viewmodel is very useful.
But, then talking between activity and ALL fragments, how could a shared ViewModel be used? Each fragment needs its own complex ViewModel. Could it be a GeneralViewModel which gets instantiated in the activity and in all fragments, together with the regular fragment viewmodel, so have 2 viewmodels in each fragment.
Being able to talk between fragments and activity with a viewmodel will make the finding of active fragment unneeded as the viewmodel will provide the needed mechanism and also would allow to use Navigation component.
Any information is gladly received.
Later edit. Here is some sample code based on the comment bellow. Is this a solution for my question? Can this handle both changes between fragments and parent activity and it's on the recommended side.
private class GlobalViewModel ():ViewModel(){
var eventFromActivity:MutableLiveData<Event>
var eventFromFragment:MutableLiveData<Event>
fun setEventFromActivity(event:Event){
eventFromActivity.value = event
}
fun setEventFromFragment(event:Event){
eventFromFragment.value = event
}
}
Then in my activity
class HomeActivity: AppCompatActivity(){
onCreate{
viewModel = ViewModelProviders.of(this, factory)
.get(GlobalViewModel::class.java)
viewModel.eventsFromFragment.observe(){
//based on the Event values, could update toolbar title, could start
// new fragment, could show a dialog or snackbar
....
}
//when need to update the fragment do
viewModel.setEventFromActivity(event)
}
}
Then in all fragments have something like this
class FragmentA:Fragment(){
onViewCreated(){
viewModel = ViewModelProviders.of(this, factory)
.get(GlobalViewModel::class.java)
viewModel.eventsFromActivity.observe(){
// based on Event value, trigger a fun from the fragment
....
}
viewModelFragment = ViewModelProviders.of(this, factory)
.get(FragmentAViewModel::class.java)
viewModelFragment.some.observe(){
....
}
//when need to update the activity do
viewModel.setEventFromFragment(event)
}
}
I'm learning about fragments I have some doubts. Consider following code:
FragmentManager fm = getFragmentManager();
Fragment MyFragment = new Fragment();
fm.beginTransaction().replace(R.id.my_container, MyFragment).addToBackStack(null).commit();
My question is:
what exactly does replace do?
What happens if I create many fragments this way (to replace previous ones in a container).
Can it in any way be bad for memory usage?
Is it considerably better just to change fragment's content?
Replace removes all the fragments that are in the container and adds the new fragment to the container. (if there isn't a fragment in the container then it just adds the new one).
If you create many fragments this way then every transaction is saved to the backstack so you can reverse the transaction by pressing the back button.
The only thing you can do is to create a variable fragmentTransaction and use the fm.beginTransaction() only once and not every time you want to replace the fragment in the container.
I don't think so, fragments should be modular and reusable.
You can read more here:
https://developer.android.com/guide/components/fragments.html
it simple put another "layer" on container.
appcrash
yes
No, fragment is the easiest way.
Using fragment & backstack tag to reference to a Fragment if you want to call fragment again and process Back button.
fm.beginTransaction().replace(R.id.my_container, MyFragment, "FRAGMENT_TAG").addToBackStack("FRAGMENT_BACKSTACK_TAG").commit();
I have an activity where I dynamically replace fragments:
private void goToFragment(Fragment newFragment, String tag) {
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.fragment_container, newFragment, tag);
ft.addToBackStack(null);
ft.commit();
}
Now, I want to access the views inside the fragment so I can put data (that I have stored in my activity) into them, immediately after calling goToFragment.
The problem is, the fragment's onCreateView isn't called before the fragment is rendered completely, at least to my understanding.
I know overriding the onAttach(Activity activity) in the fragment is one way to go about it, but then I have to cast it specifically to my activity - and I just want to avoid that because I consider it bad practice for the fragment to be dependent on a specific activity.
As far as I can see, Fragment doesn't have any listeners (as a subject) implemented.
So I figure I have to make my own listener (Using the Observer Pattern to make the fragment a subject and the activity an observer), and then calling it whenever the onCreateView or onAttach is done, and then finally calling back to the fragment with the data that needs to be set. However, I need to do this for several fragments so I would have to make a listener for each fragment, which I again think is bad.
Is there any better/easier way to do this?
FragmentTransaction isn't applied instantly after calling commit(). You may force update manually:
...
mFragmentManager.executePendingTransactions();
AFAIK event callbacks' purpose is custom communication with Fragment beyond it's usual lifecycle.
The correct way to do it would be to define an interface for Activity classes wishing to display your Fragment should implement. That way, on onAttach you don't cast to a specific Activity but to your interface.
See for instance: http://developer.android.com/guide/topics/fundamentals/fragments.html#EventCallbacks
You should use onActivityCreated to set the values.
Set references in onCreateView and then set values to them in onActivityCreated.