LiveData not updating data from one Activity to another Activity - Android

你说的曾经没有我的故事 提交于 2019-12-07 07:32:04

问题


I have 2 Activity viz

  1. List Activity
  2. Detail Activity

The list Activity shows list of items and detail Activity is shown on clicking an item from the list. In the ListActivity we observe for fetching the feeds from the DB and once we do, we update the UI.

List page

feedViewModel.getFeeds().observe(this, Observer { feeds ->
      feeds?.apply {
            feedAdapter.swap(feeds)
            feedAdapter.notifyDataSetChanged()
      }
})

Now we have a DetailActivity page which updates the feed (item) and Activity is finished but the changes are not reflected in the ListActivity.

Details page

override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        feedViewModel.setFeedId(id)
        feedViewModel.updateFeed()
}

Feed View Model

class FeedViewModel(application: Application) : AndroidViewModel(application) {


    private val feedRepository = FeedRepository(FeedService.create(getToken(getApplication())),
            DatabaseCreator(application).database.feedDao())

    /**
     * Holds the id of the feed
     */
    private val feedId: MutableLiveData<Long> = MutableLiveData()

    /**
     * Complete list of feeds
     */
    private var feeds: LiveData<Resource<List<Feed>>> = MutableLiveData()

    /**
     * Particular feed based upon the live feed id
     */
    private var feed: LiveData<Resource<Feed>>

    init {
        feeds = feedRepository.feeds
        feed = Transformations.switchMap(feedId) { id ->
            feedRepository.getFeed(id)
        }
    }

    /**
     * Get list of feeds
     */
    fun getFeeds() = feeds

    fun setFeedId(id: Long) {
        feedId.value = id
    }

    /**
     * Update the feed
     */
    fun updateFeed() {
        feedRepository.updateFeed()
    }

    /**
     * Get feed based upon the feed id
     */
    fun getFeed(): LiveData<Resource<Feed>> {
        return feed
    }

}

For simplicity purpose some code has been abstracted. If required I can add them to trace the problem


回答1:


After lots of investigation and some idea from this answer from another question. I figured out the issue.

Issue

The DatabaseCreator(application).database.feedDao() was not creating singleton instance of the database due to which the first Activity had another instance where LiveData was listening for changes and 2nd Activity had another instance where after updating the data the callback was ignored.

Solution

Use Dagger or any other dependency injection to insure only single instance of DB and DAO is created.




回答2:


I was facing this same issue across multiple activities for same entities. To me was useful to code Room Database instance as a Singleton, like : this (step 5)

Example:

public abstract class MyDatabase extends RoomDatabase {
    private static MyDatabase mMyDatabase;
    public static MyDatabase getInstance(Context context) {
        if(mMyDatabase==null){
            mMyDatabase = Room.databaseBuilder(context.getApplicationContext(), MyDatabase.class, "app_database").build();
            return mMyDatabase;
        }
    }
}

And in every ViewModel you have (class extends from AndroidViewModel for Context parameter):

    public MyViewModel(@NonNull Application application) {
        super(application);
        mMyDatabase = MyDatabase.getInstance(application.getApplicationContext());
}

Now, in my case, every time I edit a value in configuration activities it get reflected in other activities.

Hope this help.



来源:https://stackoverflow.com/questions/45196872/livedata-not-updating-data-from-one-activity-to-another-activity-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!