1

I have read this topic but I didn't understand anything. So please don't remove this question and answer me. I have a Fragment that it intents to another Activity. In the Fragment I use getLifecycleOwner as lifecycle owner of rooms observer. When I go to the Activity, I use this as Lifecycle owner but the Application crashes and shows me this error: Cannot add the same observer with different lifecycles Error.

This is observer's lifecycle owner of the fragment: productViewModel.getLiveEditedValue().observe(getViewLifecycleOwner(), s -> productRecyclerViewAdapter.notifyDataSetChanged());

And this is the observer in the Activity:

dbViewModel.getAllNews().observe(this, new Observer<List<NewsLetter>>() {
            @Override
            public void onChanged(List<NewsLetter> newsLetters) {
                if(newsLetters == null || newsLetters.isEmpty()){
                    getAllNews(BaseCodeClass.CompanyID,1577865695);
                }else{
                    Toast.makeText(getApplicationContext(),"Has data",Toast.LENGTH_SHORT).show();
                }
            }
        });

So what should I do?

I know this question has been answered before but first, I didn't understand and second I believe that was not my answer.

1 Answers1

0

In the Fragment, use:

[Kotlin]

val owner = activity as LifeCycleOwner
productViewModel.getLiveEditedValue().observe(owner, Observer { s ->
    // UI update here
})

[Java]

LifecycleOwner owner = (LifecycleOwner) getActivity();
productViewModel.getLiveEditedValue().observe(owner, s -> productRecyclerViewAdapter.notifyDataSetChanged());
yoninja
  • 1,952
  • 2
  • 31
  • 39