MutableLiveData 设置值但 getValue() returns 为空?

MutableLiveData sets value but getValue() returns null?

我在将我的项目迁移到 androidx 后遇到了这个问题。在迁移之前这一切都像一个魅力 (我 不得不 迁移我的项目) 但现在我站在这个 10 分钟前不存在的奇怪问题面前.

场景: 片段 1 包含项目的列表视图,当用户单击项目时,我调用我的视图模型 setvalue() 方法,然后片段 2 似乎显示用户单击的项目,为此我调用我的视图模型 getvalue()。场景很简单

片段 1:

@Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        viewModel.getClickedSong().setValue(viewModel.getSongs().getValue().get(position));

视图模型:

public MutableLiveData<Song> getClickedSong() {
    if (clickedSong == null) {
        clickedSong = new MutableLiveData<>();
    }
    return clickedSong;
}

片段 2:

viewModel.getClickedSong().observe(this, new Observer<Song>() {
                @Override
                public void onChanged(Song song) {
                    mySong = song;

我也尝试过:mySong = viewModel.getClickedSong().getValue() 但这也是 returns null。

经过数小时的研究、测试等,修复非常简单。

我更改了这行代码:

viewModel = ViewModelProviders.of(this).get(SharedViewModel.class);

为此:

viewModel = ViewModelProviders.of(getActivity()).get(SharedViewModel.class);