Implementing the new Android Architecture Components with Activity and Fragments

563 Views Asked by At

Currently I try implementing an application with the architecture components provided by android. In terms of only using activities in the UI Package there is no problem with that, but if I implement several fragments which are held by one activity in a fragment container I'll get in trouble. The communication for data requests using fragments should never be called from the fragments itself but from its activity. In this case only the activity will register the needed viewmodel but the lifecycle of each fragment isn't handled properly... how can I face this problem using multiple fragments in one activity requesting data from a server and be lifecycleaware for the fragments even when the activity is calling the viewmodel(s)?

3

There are 3 best solutions below

3
On BEST ANSWER

I´m not sure if I understood you right. You want to load data in your Activity for your Fragment with the lifecycle awareness of your Fragment?

Maybe you can try to access the ViewModel of your Fragment from the Activity to get an FragmentLifecycle aware ViewModel. And than you can query data via this ViewModel.

viewModel = ViewModelProviders.of(YourFragment).get(FragmentViewModel.class);

I´m not sure if this works or if this is a good idea. The google guide only shows it the other way around, accessing the ViewModel from the Activity within the Fragment, to share data between Fragments, or Activity and Fragment.

0
On

@Rahul Khurana

public class UserProfileFragment extends LifecycleFragment {
private static final String UID_KEY = "uid";
private UserProfileViewModel viewModel;

@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    String userId = getArguments().getString(UID_KEY);
    viewModel = ViewModelProviders.of(this).get(UserProfileViewModel.class);
    viewModel.init(userId);
}

@Override
public View onCreateView(LayoutInflater inflater,
            @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    return inflater.inflate(R.layout.user_profile, container, false);
}

As you can see the fragment is directly communicating with the viewmodel which is a request for data or setting some new data. This action is lifecycle aware but I know that its mandatory to communicate with the datalayer through the activity? This is a code snippet from the official android page

2
On

Have you heard of Interface Listener. This will help you in all the ways no matter how much complications are there. If you are still confused do let me know