Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Refresh fragment on back to previous fragment

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 !!

like image 777
Adham Gamal Avatar asked Oct 16 '22 04:10

Adham Gamal


1 Answers

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

like image 96
Adham Gamal Avatar answered Oct 27 '22 09:10

Adham Gamal