ViewModel观察器方法返回null

时间:2018-11-07 05:34:23

标签: android viewmodel android-livedata

我遇到以下错误

Attempt to invoke virtual method 'void android.arch.lifecycle.LiveData.observe on a null object reference

摘自我的主要片段的以下这段代码

    mReleasesViewModel = ViewModelProviders.of(this).get(ReleasesViewModel.class);
    mReleasesViewModel.getUpcomingReleases(filter).observe(this, new Observer<List<_Release>>() {
        @Override
        public void onChanged(@Nullable List<_Release> releases) {
            // whenever the list is changed
            if (releases != null) {
                mUpcomingGamesAdapter.setData(releases);
                mUpcomingGamesAdapter.notifyDataSetChanged();
            }
            mDatabaseLoading.setVisibility(View.GONE);
        }
    }); 

该错误专门在此行上抛出(当我附加观察者时)

mReleasesViewModel.getUpcomingReleases(filter) ...

我的ViewModel类:

public class ReleasesViewModel extends ViewModel {
    // fragment name and list
    private HashMap<String, MutableLiveData<List<_Release>>> upcomingReleasesListMap = new HashMap<>();

    private ReleasesRepository releasesRepository;
    private ArrayList<Integer> platforms;
    private String region;

    public ReleasesViewModel() {
        // Shared to all fragments : User settings region & platforms
        region = SharedPrefManager.read(SharedPrefManager.KEY_PREF_REGION, "North America");
        Set<String> defaultPlatformsSet = new HashSet<>();
        platforms = SharedPrefManager.read(SharedPrefManager.PLATFORM_IDS, defaultPlatformsSet);
    }

    public MutableLiveData<List<_Release>> getUpcomingReleases(String filter) {
        // ReleasesRepository takes a different monthly filter
        releasesRepository = new ReleasesRepository(region, filter, platforms);

        if (upcomingReleasesListMap.containsKey(filter)) {
            // Double check if it isn't null, just in case
            if (upcomingReleasesListMap.get(filter) == null) {
                // if null; try again to send a new request
                loadReleases(filter);
            } // else just don't do anything, the list is already in the Map
        } else {
            // Load it in if this filter was never added to the map [New filter and new list]
            loadReleases(filter);
        }
        return upcomingReleasesListMap.get(filter);
    }


    private void loadReleases(final String filter) {
        releasesRepository.addListener(new FirebaseDatabaseRepository.FirebaseDatabaseRepositoryCallback<_Release>() {
            @Override
            public void onSuccess(List<_Release> result) {
                // sort by release date
                if (platforms.size() > 1) {
                    // Will only sort for multiple platforms filter
                    Collections.sort(result);
                }
                MutableLiveData<List<_Release>> releases = new MutableLiveData<>();
                releases.setValue(result);
                upcomingReleasesListMap.put(filter, releases);
            }

            @Override
            public void onError(Exception e) {
                // Log.e(TAG, e.getMessage());
                MutableLiveData<List<_Release>> releases = new MutableLiveData<>();
                releases.setValue(null);
                upcomingReleasesListMap.put(filter, releases);
            }
        });
    }
}

Hashmap是我将数据提供给片段的必不可少的部分。由于我现在要在应用程序中维护6个片段,因此我需要对所有6个片段使用一个ViewModel。每个片段都有一个带有相同类型数据(对象和视图)的recyclerview,但是它们对数据应用了不同的过滤器。请查看ViewModel中的String filter参数,此参数将过滤器应用于数据。当然,我将在ViewModel中保留所有6个片段。因为它们都需要同时进行更新(当用户完成诸如更改platforms列表之类的操作时)

1 个答案:

答案 0 :(得分:1)

您拥有异步代码,在实现这些方法时没有考虑这些异步代码,最后得到的是一个空LiveData,在其上调用watch()引发异常。您当前使用的流程:

  • 使用未知过滤器调用getUpcomingReleases()
  • 此过滤器不在地图中,因此您调用loadReleases()
  • loadReleases()仅为后台操作(firebase)设置侦听器,并立即返回
  • 您到达返回行reemingReleasesListMap.get(filter); ,这将返回null,因为firebase侦听器很可能没有完成,并且您未在该过滤器中放置任何内容值
  • 使用null的LiveData失败

您需要类似下面的代码才能使其正常工作:

public MutableLiveData<List<_Release>> getUpcomingReleases(String filter) {
   ...
   if (upcomingReleasesListMap.get(filter) == null) {
       // we don't have a mapping for this filter so create one in the map
       MutableLiveData<List<_Release>> releases = new MutableLiveData<>();
       upcomingReleasesListMap.put(filter, releases);  
       // also call this method to update the LiveData
       loadReleases(filter);
    }
    // for now just return the empty LiveData so our ui can use it
    // when the firebase listener returns we will update it
    return upcomingReleasesListMap.get(filter);
}

private void loadReleases(final String filter) {
    releasesRepository.addListener(new FirebaseDatabaseRepository.FirebaseDatabaseRepositoryCallback<_Release>() {
        @Override
        public void onSuccess(List<_Release> result) {
            // sort by release date
            if (platforms.size() > 1) {
                // Will only sort for multiple platforms filter
                Collections.sort(result);
            }
            // just use the previous created LiveData, this time with the data we got 
            MutableLiveData<List<_Release>> releases = upcomingReleasesListMap.get(filter);
            releases.setValue(result);
        }

        @Override
        public void onError(Exception e) {
            // Log.e(TAG, e.getMessage());
            MutableLiveData<List<_Release>> releases = upcomingReleasesListMap.get(filter);
            releases.setValue(null);                
        }
    });
}