How to get LifecycleOwner in a Fragment?

AlexKTP picture AlexKTP · Oct 17, 2019 · Viewed 7k times · Source

I need to get the LifecycleOwner to pass it in my FirestoreRecyclerViewOption but Fragment doesn't implement Lifecycle.

So, how to get that?

My Fragment implements LifecycleOnwer as shown in the following code example,

public class ListRestFragment extends Fragment implements LifecycleOwner 

after in the onCreateMethod,

  lifecycleRegistry = new LifecycleRegistry(this);
        lifecycleRegistry.setCurrentState(Lifecycle.State.CREATED);

and to finish

@Override
    public void onStart() {
        super.onStart();
        lifecycleRegistry.setCurrentState(Lifecycle.State.STARTED);
    }

    @NonNull
    @Override
    public Lifecycle getLifecycle() {
        return lifecycleRegistry;
    }

I follow this example but it doesn't work

Attempt to invoke virtual method 'androidx.lifecycle.Lifecycle$State androidx.lifecycle.Lifecycle.getCurrentState()' on a null object reference

I need it to edit My FirestoreRecyclerViewOption and setLifeCycleOwner because it is always null and I have an NullPointer everytime.

Answer

Sina picture Sina · Oct 17, 2019

Update: Actually it is better to use getViewLifeCycleOwner if you are using views in your observers. Because the view might not exist when the LiveData gets updated and you want to change the view(e.g. changing visibility of a view) which causes crashes.

The fragment itself is the LifecycleOwner you are looking for. You can use keyword "this" as a reference to the fragment.

Read this: "Lifecycle is a class that holds the information about the lifecycle state of a component (like an activity or a fragment) and allows other objects to observe this state."

And: "LifecycleOwner is a single method interface that denotes that the class has a Lifecycle."