RecyclerView don't show inserted SQLite data instantly

前端 未结 1 1314
无人共我
无人共我 2021-01-28 02:47

When the user from a FragmentDialog type his data into the edittexts and press the save button, the data should instantly show in the recyclerView, but

相关标签:
1条回答
  • 2021-01-28 03:42

    You should use a CursorLoader which automatically listens for changes in Uri. And notify changes via contentResolver.notifyChanged(uriOfInsertedData). The beast way is to use a ContentProvider to make all thins thing work appropriately.

    Or for an easier way, register an Observer in a singleton for your database and notify it upon changing. In general this will do the same and you will not have any relations between components. It takes some code to post so I hope you will figure it out.

    Update 2016-03-09, based on your comment

    If you implemented example 1, it doesn't tell you how to monitor for changes. There is no existing mechanism for this case.

    The best approach to implement this mechanism is to use an Observer pattern.

    I would go with a singleton that hosts Observers.

    You can extend Observable (which already has logic for storing a list of Observers, notifying and removing them) and make a singleton of it.

    Register Observer by calling addObserver() wherever you need to listen to (don't forget to call deleteObserver() to avoid Activity leaks).

    Now, whenever you call insert or modify a database in any way, make sure to call notifyObservers("tablename") of Observable singleton.

    This way all observers will get notified the table was modified (passing a table name is an example, you can use any Object there to inform your components about the change)

    Then in update() of your Observer, check if the table you wish to monitor is updated, if so, reload the data as you normally would do.

    0 讨论(0)
提交回复
热议问题