Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get LifecycleOwner in a Fragment?

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.

like image 495
Alek KT Avatar asked Dec 08 '22 11:12

Alek KT


2 Answers

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."

like image 152
Sina Avatar answered Dec 11 '22 09:12

Sina


In fragments you can use getViewLifecycleOwner() method to get the lifeCycleOwner.

like image 36
Parisa Baastani Avatar answered Dec 11 '22 10:12

Parisa Baastani