gpt4 book ai didi

android - LiveData 没有将数据从一个 Activity 更新到另一个 Activity - Android

转载 作者:行者123 更新时间:2023-12-05 00:50:53 24 4
gpt4 key购买 nike

我有 2 Activity

  • 列表 Activity
  • 详情 Activity

  • 名单 Activity显示项目列表和详细信息 Activity在单击列表中的项目时显示。
    ListActivity我们观察从数据库中获取提要的情况,一旦这样做,我们就会更新 UI。

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

    现在我们有一个 DetailActivity更新提要(项目)和 Activity 的页面已完成,但更改未反射(reflect)在 ListActivity 中.

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

    饲料 View 模型
    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
    }

    }

    为简单起见,一些代码已被抽象出来。如果需要,我可以添加它们以跟踪问题

    最佳答案

    经过大量调查和来自 this answer 的一些想法从另一个问题。我弄清楚了这个问题。

    问题
    DatabaseCreator(application).database.feedDao()由于第一个 Activity 没有创建数据库的单例实例有另一个实例,LiveData正在监听变化,第二个 Activity还有另一个实例,在更新数据后,回调被忽略。

    解决方案

    使用 Dagger 或任何其他依赖注入(inject)来确保仅创建 DB 和 DAO 的单个实例。

    关于android - LiveData 没有将数据从一个 Activity 更新到另一个 Activity - Android,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45196872/

    24 4 0